DEV Community

Cover image for sticky navbar on scroll reactJS

sticky navbar on scroll reactJS

Abod Micheal (he/him) on October 12, 2020

Basically showing how you could achieve the bellow Navbar in react . firstly you need to create a file then name it Navbar, add import from '...
Collapse
 
gabrielmlinassi profile image
Gabriel Linassi •

Thanks! I created a version for functional components:

const [show, setShow] = useState(false);

useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);

const handleScroll = () => {
setShow(window.pageYOffset > 140);
};

Collapse
 
abodmicheal profile image
Abod Micheal (he/him) •

nice thanks for that I'll add and give credit , working on a library for it

Collapse
 
sapardo profile image
Sebastian Pardo •

Hey, a newbie here. Got a question with your React code.
Shouldn't you have a constructor inside a class component??

Collapse
 
abodmicheal profile image
Abod Micheal (he/him) •

only if you're passing prop

Collapse
 
sapardo profile image
Sebastian Pardo •

ahhh i see!
Thanks for your response. ♥

Thread Thread
 
abodmicheal profile image
Abod Micheal (he/him) •

wish you luck , react is actually easy and interesting, All the best

Collapse
 
nescalan profile image
Nelson González Escalante •

Good work, thank you

Collapse
 
alexb801 profile image
Alex •

Wasn't able to run this. Probably due to out of date?

Collapse
 
abodmicheal profile image
Abod Micheal (he/him) •

I made a library out of this, check it out

Collapse
 
abodmicheal profile image
Abod Micheal (he/him) •

still used it today for a project

Collapse
 
talah221 profile image
talah221 •

Great rhanks