I am creating a navigation bar with React that visually highlights the active component when it is scrolled into view by the user. So, they scroll to the 'About' component and the user icon would highlight and the home icon would return to normal. It looks like this:
I am trying to do this in 2 steps: (1) using the useInView hook in my App.jsx component to set the 'activeElement' with a useState hook when the user scrolls to the useInView {ref}, and (2) passing the 'activeElement' as a useState variable to the child Nav component via props and useEffect to update activeNav in the Nav component when the user is scrolling.
Here is my code for the App component, which I have been testing within the paragraph tags. Currently, activeElement is not being affected by scrolling.
const App = () => {
const { ref, inView, entry } = useInView({
/* Optional options */
threshold: 0,
});
const [activeElement, setActiveElement] = useState('#')
return (
<>
<Header ref={ref} setActiveElement={inView ? '#home' : '' }/>
<Nav activeElement={activeElement}/>
<About ref={ref} setActiveElement={inView ? '#about' : '' } />
<p>{activeElement}</p>
<Services ref={ref} setActiveElement={inView ? '#services' : '' } />
<Contact ref={ref} setActiveElement={inView ? '#contact' : '' }/>
<Footer />
<p>{activeElement}</p>
</>
)
}
export default App
And here is the code for my Nav component:
const Nav = ({activeElement}) => {
const [activeNav, setActiveNav] = useState('#');
useEffect(() => {
setActiveNav(activeElement);
})
return (
<nav>
<a href="#" onClick={() => setActiveNav('#')} className={activeNav === '#' ? 'active' : ''}><AiOutlineHome /></a>
<a href="#about" onClick={() => setActiveNav('#about')} className={activeNav === '#about' ? 'active' : ''}><AiOutlineUser /></a>
<a href="#experience" onClick={() => setActiveNav('#experience')} className={activeNav === '#experience' ? 'active' : ''}><HiOutlineBookOpen /></a>
<a href="#services" onClick={() => setActiveNav('#services')} className={activeNav === '#services' ? 'active' : ''}><FaUncharted /></a>
<a href="#contact" onClick={() => setActiveNav('#contact')} className={activeNav === '#contact' ? 'active' : ''}><RiMessage2Line /></a>
</nav>
)
}
export default Nav
What is wrong with my useInView execution? And am I passing the activeElement variable to the Nav component correctly?
Thanks for taking the time to read this through.