how to change navigation link active class on scroll in 'React' or how to change the window.loaction.hash on scroll in react

Viewed 889

I am using react, I am building a single page application and I don't want to use react-router I just have one page and sections , and a hash for each section (or component in react ) , I want the active navigation-link to change on scroll, or I want to change the window location hash on scroll so that the active class will work on scroll.... please help

  const ref = React.useRef(null);
 

  const handleScroll = () => {
    if (ref.current ) {
      setSticky(ref.current.getBoundingClientRect().top <= 0);
    }
    

  };

  
  React.useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    window.addEventListener("scroll", () => {
      setScroll(window.scrollY > 200 );
  
    });
   
    return () => {
      window.removeEventListener('scroll', () => handleScroll);
    };
    
  }, []);
    return (<Container fluid className='p-0'>
<Navbar  ref={ref}  fixed={isSticky ? 'top': '' } className='nav_bar ' expand="lg">
  <Navbar.Toggle  aria-controls="basic-navbar-nav" ><FontAwesomeIcon style={{color:'#fff'}} icon={faBars}/></Navbar.Toggle>
  <Navbar.Collapse id="basic-navbar-nav">
  <Nav className='ml-5'>
  <Nav.Item>
    <Nav.Link  className={`${scroll  ? 'active':''} nav_link px-5`}   href="#home">home</Nav.Link>
  </Nav.Item>
  <Nav.Item>
    <Nav.Link  className={`${scroll   ? 'active':''} nav_link px-5`} href='#about' >about</Nav.Link>
  </Nav.Item>
  <Nav.Item>
    <Nav.Link  className={`${scroll   ? 'active':''} nav_link px-5`} href='#portfolio' >portfolio</Nav.Link>
  </Nav.Item>
  <Nav.Item>
    <Nav.Link  className={`${scroll   ? 'active':''} nav_link px-5`} href='#contact' > contact
    </Nav.Link>
  </Nav.Item>
</`Nav`>
  </`Navbar.Collapse`>
</`Navbar`></Container>
        );
}
i tried this method but i failed and all links show active at once
0 Answers
Related