![]() |
VOOZH | about |
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 hook.
Prerequisite:
To create a scroll to top button in react we will use the JavaScript scrollTo method. Define a scroll button and toggle its visibility at some scroll point. Define a function scroll to top using link it to click event in scroll to top button. We will use styled-components for styling the button and the components.
You will start a new project using create-react-app so open your terminal and type.
npx create-react-app react-scroll-topNow go to your react-scroll-top folder by typing the given command in the terminal.
cd react-scroll-topInstall 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.
The file structure in the project will look like this.
👁 ImageThe updated dependencies in the package.json file are:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-icons": "^5.3.0",
"react-scripts": "5.0.1",
"styled-components": "^6.1.13",
"web-vitals": "^2.1.4"
},
Example: This example demonstrates how to create scroll to top button with the help of scrollTo method and useState to toggle the button visibility.
Step to Run Application: Run the application using the following command from the root directory of the project:
npm startOutput: Now open your browser and go to http://localhost:3000/, you will see the following output.