I am sharing here a “GoToTop” React JS component that I created today. This component will render a button (shaped as an arrow) when the user scrolls down, past a certain point. When clicked, this button will execute a handleGoToTop() function that will smoothly scroll the screen back to the top.
This is a styled component, making it very portable. It also uses React hooks and TypeScript.
1. The “GoToTop” component
// src/components/GoToTop/index.tsx import React, { useState, useEffect } from 'react'; import { Container } from './styles'; const GoToTop: React.FC = () => { const [scrolled, setScrolled] = useState(false); useEffect(() => { window.addEventListener('scroll',() => { const isTop = window.scrollY < 150; isTop !== true ? setScrolled(true) : setScrolled(false); }) }, []); function handleGoToTop() { window.scrollTo({ top: 0, behavior: "smooth" }); } return ( <> <Container> { scrolled && <button id="goToTop" onClick={() => handleGoToTop()} title="Go to top"></button> } </Container> </> ); } export default GoToTop;
Read more ““GoToTop”: a (scroll to top elevator) styled component for React JS with TypeScript”