I want to make sticky navigation in Gatsby. I could just make a separate script and reference the element I need to reference, but that seems counter-intuitive for a component pattern.
So I want to reference the Element from inside the component, but I hit a wall. If I use document.querySelector(".primaryNavigation")
I get null
, so my question is:
How do I reference a component element from within a functional component such as below?
export default function PrimaryNavigation() {
window.onscroll = () => {
// reference the nav element here
}
return (
<nav className="primaryNavigation">
<ul>
<li>
<Link to="/blog">Blog</Link>
</li>
</ul>
</nav>
);
}
As Derek suggested, I should look into and use ref
I'll show an example of what I did to solve the problem here.
export default function Navigation() {
const nav = React.createRef();
window.onscroll = function() {
if(window.pageYOffset > nav.current.offsetTop)
nav.current.style = "position:fixed;top:0;width:100%";
else
nav.current.style = "";
}
return (
<nav ref={nav}>
<ul>
<li><Link to="/whatever">Whatever</Link></li>
</ul>
</nav>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.