How to change the navbar color when you scroll in ReactJS ?
On scroll navbar color change in React highlights a sticky responsive navigation bar to navigate through web application pages. It provides an efficient way to navigate multiple pages in a single-page application. 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.
Prerequisites
Approach for Nav Bar color change on scroll in React
This approach includes the use of an event listener and DOM window.scrollY function for scroll condition to change the navbar color in react.
Steps to create the application
Step 1: Create a React application using the following command.
npx create-react-app navbar-color-change
Step 2: After creating your project folder i.e. navbar-color-change, move to it using the following command.
cd navbar-color-change
Step 3: Install the dependencies required in this project by typing the given command in the terminal:
npm i --save styled-components 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:
Dependency list after installing libraries
{
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^4.11.0",
"react-scripts": "5.0.1",
"styled-components": "^6.1.0",
"web-vitals": "^2.1.4"
}
}
Example: we will design a navbar with a useState variable named colorChange. 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 with the help of window.scrollY function.
- Javascript
- Javascript
- Javascript
- CSS
Javascript
// App.js import React, { Fragment } from "react" ; import Navbar from "./components/Navbar" ; function App() { return ( <Fragment> <Navbar /> <div style={{ overflowY: "scroll" , height: "800px" , }} ></div> </Fragment> ); } export default App; |
Javascript
Javascript
CSS
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: See how navbar changes its color to black on scrolling down and becomes transparent again on returning to the top. Thi soutput will be visible on https://localhost:3000/ on browser.