How to create a Scroll To Top button in React JS ?
You will see there are lots of websites, that are using a useful feature like if you’re scrolling the webpage, and now you are at the bottom of that page then you can use this button to scroll up automatically like skip to the content. The following example covers create a Scroll To Top button in React JS using useState() hook.
- Basic knowledge of npm & create-react-app command.
- Basic knowledge of styled-components.
- Basic Knowledge of useState() React hooks.
Basic Setup: You will start a new project using create-react-app so open your terminal and type.
npx create-react-app react-scroll-top
Now go to your react-scroll-top folder by typing the given command in the terminal.
Required module: Install the dependencies required in this project by typing the given command in the terminal.
npm install --save styled-components npm install --save react-icons
Now create the components folder in src then go to the components folder and create two files ScrollButton.js and Styles.js.
Project Structure: The file structure in the project will look like this.
Example: In this example, we will design a webpage with Scroll To Top button, for that we will need to manipulate the App.js file and other created components file.
We create a state with the first element visible as an initial state having a value of the false and the second element as function setVisible() for updating the state. Then a function is created by the name toggleVisible which sets the value of the state to true when we scroll down the page more than 300px ( you can choose any value as per your choice). Otherwise, the state value is set to false.
Then a function is created by the name scrollToTop in which we use the scrollTo method to scroll our page to the top. When we scroll down the page more than 300px, the function toggleVisible gets triggered as an event through window.addEventListener property and sets the state visible to true. Now our state is used to show the Scroll to top icon to the user. When the user clicks on this icon, the function scrollToTop gets triggered as an onClick() event which scrolls our page smoothly to the top. You can also use ‘auto’ behavior in place of ‘smooth’.
Step to Run Application: Run the application using the following command from the root directory of the project:
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
- Using default behavior (auto): See how it directly jumps to the top.
- Using smooth behavior: See how it goes smoothly to the top.