Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to change the navbar color when you scroll in ReactJS ?

  • Difficulty Level : Medium
  • Last Updated : 26 Feb, 2021

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.

Prerequisite:

  1. This article is written by you so there will no issue with improving manually.
  2. 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:

cd navbar-color-change

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.



NavBar.js




import React, { useState, Fragment } from 'react'
import { FaBars } from 'react-icons/fa'
import {
  Nav,
  NavContainer, 
  NavLogo,
  NavItem,
  NavLinks,
  NavMenu,
  MobileIcon,
} from './NavbarStyles';
import '../App.css';
const Navbar = () => {
  const [colorChange, setColorchange] = useState(false);
  const changeNavbarColor = () =>{
     if(window.scrollY >= 80){
       setColorchange(true);
     }
     else{
       setColorchange(false);
     }
  };
  window.addEventListener('scroll', changeNavbarColor);
  return (
      <Fragment>
        <Nav className={colorChange ? 'navbar colorChange' : 'navbar'}>
           <NavContainer>
              <NavLogo href="#">GeeksForGeeks</NavLogo>
              <MobileIcon>
               <FaBars />
              </MobileIcon>
              <NavMenu>
                <NavItem>
                  <NavLinks href="#">About</NavLinks>
                </NavItem>
                <NavItem>
                  <NavLinks href="#">Services</NavLinks>
                </NavItem>
                <NavItem>
                  <NavLinks href="#">Events</NavLinks>
                </NavItem>
                <NavItem>
                  <NavLinks href="#">Contact</NavLinks>
                </NavItem>
                <NavItem>
                  <NavLinks href="#">Sign In</NavLinks>
                </NavItem>
              </NavMenu>
           </NavContainer>
        </Nav>
      </Fragment>
    )
}
  
export default Navbar;

NavbarStyles.js




import styled from 'styled-components';
export const Nav = styled.nav`
   background: transparent;
   height: 80px;
   display: flex;
   justify-content: center;
   align-items: center;
   font-size: 1rem;
   /* Fix your navbar by using below two lines of code */
   position: sticky;
   top:0;
   /* Fix your navbar by using above two lines of code */
   z-index: 10;
  
   @media screen and (max-width: 960px) {
       transition: 0.8s all ease
   }
`;
  
export const NavContainer = styled.div`
   display: flex;
   justify-content: space-between;
   height: 80px;
   z-index: 1;
   width: 100%;
   padding: 0 24px;
   max-width: 1100px;
`;
  
export const NavLogo = styled.a`
   color: green;
   justify-self: flex-start;
   cursor: pointer;
   font-size: 1.5rem;
   display: flex;
   align-items: center;
   margin-left: 24px;
   font-weight: bold;
   text-decoration: none;
`;
  
export const MobileIcon = styled.div`
   display: none;
  
   @media screen and (max-width: 768px) {
    display: block;
    position: absolute;
    top:0;
    right: 0;
    transform: translate(-100%, 60%);
    font-size: 1.8rem;
    cursor: pointer;
   }
`;
  
export const NavMenu = styled.div`
   display: flex;
   align-items: center;
   list-style: none;
   text-align: center;
   margin-right: -22px;
  
   @media screen and (max-width: 960px) {
     display: none;
  }
`;
  
export const NavItem = styled.li`
   height: 80px;
`;
  
export const NavLinks = styled.a`
   color: #808080; 
   display: flex; 
   align-items: center; 
   text-decoration: none; 
   padding: 0 1rem; 
   height: 100%; 
   cursor: pointer; 
   &.active { 
  color: #000000; 
  
`

App.css




.navbar{
    background-color: transparent;
}
  
.navbar.colorChange{
    background-color: #000;
}

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;

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!