Library for auto scroll detect.
Unanswered
Sun bear posted this in #help-forum
Sun bearOP
I have a single page application that has 4 sections: hero, about, food menu, contact. I also have a navigation in my header that points to each of these except for hero.
I want to highlight the button in header when the user reaches the section or clicks on it. What would be your approach for this and are there some libraries to make this simpler and more production ready.
I want to highlight the button in header when the user reaches the section or clicks on it. What would be your approach for this and are there some libraries to make this simpler and more production ready.
function Header() {
const [current, setCurrent] = useState<string | null>(null)
return (
<NavBar>
<ButtonLink variant={current === "#about" ? "primary" : "ghost"}>About</ButtonLink>
<ButtonLink variant={current === "#food-menu" ? "primary" : "ghost"}>Food Menu</ButtonLink>
<ButtonLink variant={current === "#contact" ? "primary" : "ghost"}>Contact</ButtonLink>
</NavBar>
)
}
function HomePage() {
return (
<>
<section id="hero" />
<section id="about" />
<section id="food-menu" />
<section id="contact" />
</>
)
}4 Replies
North Pacific hake
it should work with Intersection Observer with adding id(#hero,...etc) to each of the div. (No libs required)
Sun bearOP
so I would create a
useEffect calling:const [current, setCurrent] = useState<string | null>(null)
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
const [ entry ] = entries
if (entry.isIntersecting) setCurrent(entry.target)
})
const about = document.querySelector("about")
const contact = document.querySelector("contact")
observer.observe(about)
observer.observe(contact)
return () => {
observer.unobserve(about)
observer.unobserve(contact)
}
}, [])is that correct?
I really don't like calling the DOM directly from react but this seems to be the easiest option. pure react example would have me create context for the refs, complicating this alot...