Search code examples
javascriptcssreactjsscrollreact-bootstrap

How to change Bootstrap navbar color on scroll in React.js?


I am looking for a way to change the Navbar color (.bg-light in CSS) on scroll, but I couldn't find a way of doing it. I want to implement a code such that whenever the user scrolls down from the certain y point, the navbars style will change; and whenever the user scrolls up to that point it will be back to its old style.

Here is my navbar component. Any suggestions?

import React, { useState} from 'react';
import './Navbar.css';
import Navbar from 'react-bootstrap/Navbar'
import Nav from 'react-bootstrap/Nav'
import { Link, animateScroll as scroll } from "react-scroll";

const navbar = (props) =>  {

    return (
        <div>
        <Navbar bg="light" expand="sm" fixed="top">
            <Navbar.Brand href="#home">
                KuGPA
            </Navbar.Brand>
            <Navbar.Toggle aria-controls="basic-navbar-nav" />
            <Navbar.Collapse id="basic-navbar-nav ">
                    <Nav.Link className="ml-auto"/>
                    <Link to="HOME" smooth={true} duration= {500}>
                        <Nav.Link  href="#HOME">Home</Nav.Link>
                    </Link>

                    <Link to="KUGPA" smooth={true} duration= {500}>
                    <Nav.Link  href="#KUGPA">KuGPA</Nav.Link>
                    </Link>


                    <Link to="ABOUT" smooth={true} duration= {500}>
                    <Nav.Link href="#ABOUT">About</Nav.Link>
                    </Link>


                    <Link to="CONTACT" smooth={true} duration= {500}>
                    <Nav.Link  href="#CONTACT">Contact</Nav.Link>
                    </Link>
            </Navbar.Collapse>
        </Navbar>
        </div>

    );
  }


export default navbar;

Thanks


Solution

  • I Just tested this, and it worked fine.

    const [navBackground, setNavBackground] = useState(false)
        const navRef = useRef()
        navRef.current = navBackground
        useEffect(() => {
          const handleScroll = () => {
            const show = window.scrollY > 50
            if (navRef.current !== show) {
              setNavBackground(show)
            }
          }
          document.addEventListener('scroll', handleScroll)
          return () => {
            document.removeEventListener('scroll', handleScroll)
          }
        }, [])
    

    In your Navbar, remove bg="light"

     <Navbar expand="sm" fixed="top" style={{ transition: '1s ease',backgroundColor: navBackground ? 'black' : 'transparent'}}>