The following approach covers how to change the navbar color when you scroll through the page in ReactJS. It is a simple effect you can add to any ReactJS website.
- This article is written by you so there will no issue with improving manually.
- 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 navbar-color-change
Now go to your navbar-color-change 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 Navbar.js and NavbarStyles.js.
Project Structure: The file structure in the project will look like this:
Example: In this example, we will design a navbar, for that we will need to manipulate the App.js file and other created components file.
Navbar.js: Navbar Color Change Logic, that’s where the role of useState() hook comes into play.
We create a state with the first element colorChange as an initial state having a value of the false and the second element as function setColorchange() for updating the state. Then a function is created by the name changeNavbarColor which sets the value of the state colorChange to true when we scroll down the page equal to or more than 80px. This is done with the help of window.scrollY function. We have used this 80px value in accordance with the value of our navbar’s height (80px). Otherwise the state value remains false.
The value of state colorChange decides the color of our navbar with the help of a conditional operator. When our state’s value is false, it assigns a CSS class of ‘navbar’ to our Navbar component which provides it a background-color of transparent. When we scroll equal to or more than the height of our navbar (80px), the value of state colorChange becomes true, and it assigns a different CSS class of ‘navbar colorChange’ to our Navbar component which provides it a background color of #000. We will define both these CSS classes in our App.css file.
When we start scrolling down the page, the function changeNavbarColor gets triggered as an event through window.addEventListener property.
Step to Run Application: Run the application using the following command from the root directory of the project:
Output: See how navbar changes its color to black on scrolling down and becomes transparent again on returning to the top.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.