The following approach covers how to create Scroll Indicator using React JS. It is a simple effect you can add to any ReactJS website.
- Basic knowledge of npm & create-react-app command.
- Basic knowledge of styled-components.
- Basic knowledge of useState() hooks.
Basic Setup: You will start a new project using create-react-app command.
npx create-react-app react-scroll-indicator
Now go to your react-scroll-indicator 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
Now create the components folder in src then go to the components folder and create two files ScrollIndicator.js and Styles.js.
Project Structure: The file structure in the project will look like this:
Example: In this example, we will design a scroll indicator component, for that we will need to manipulate the App.js file and other created components file.
We create a state with the first element scroll as an initial state having a value of 0 and the second element as function setScroll() for updating the state. Then a function is created by the name onScroll in which we declare the following variables :
- Scrolled: It tells us how many pixels the user has scrolled down so far.
- MaxHeight: It tells us the difference between the height of the whole webpage and the height of the maximum portion of the browser that the user can see.
- ScrollPercent: It tells us the percentage value of the width of the Scroll Indicator element. It is equal to 100 multiplied with the ratio of no of pixels the user has scrolled down so far (from top) to the total no of pixels of the remaining portion of the browser which the user can only see on scrolling down.
When we start scrolling down the page, the function onScroll gets triggered as an event through window.addEventListener property. It sets the state value to ScrollPercent due to which the indicator bar starts filling up with green color when we scroll down the page. When we scroll up the page the quantity of color reduces.
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: