Next.js Discord

Discord Forum

Creating an auto-hiding, scroll aware header with useState

Unanswered
Brown bear posted this in #help-forum
Open in Discord
Brown bearOP
I'm trying to make a header that will be aware of both scroll direction and scroll position on the page.

At the moment, my code only seems to be aware of position - the direction seems to be based on the scroll position of the page when it was first loaded, rather than the current direction of the user's scroll.

My plan is to use classes to hide the header when the user scrolls down, display it when the user scrolls up, and also change background color/text colour when the page is at the very top. Does anybody have any idea how I can adapt this code to use the current scroll direction, please?

1 Reply

Brown bearOP
import { useState, useEffect } from 'react'; const ScrollAwareHeader = () => { const [scrollPosition, setScrollPosition] = useState(0); const [scrollDirection, setScrollDirection] = useState('down'); const handleScroll = () => { const header = document.getElementById('header'); const currentScrollY = window.scrollY; // Determine scroll direction const direction = currentScrollY > scrollPosition ? 'down' : 'up'; setScrollDirection(direction); // Update the scroll position setScrollPosition(currentScrollY); // Apply classes based on scroll position if (currentScrollY > 200) { header?.classList.add('scrolled'); header?.classList.remove('unscrolled'); } else { header?.classList.remove('scrolled'); header?.classList.add('unscrolled'); } // Add/remove scroll direction class if (scrollDirection === 'down') { header?.classList.add('scroll-down'); header?.classList.remove('scroll-up'); console.log(scrollDirection) } else { header?.classList.remove('scroll-down'); header?.classList.add('scroll-up'); console.log(scrollDirection) } }; useEffect(() => { window.addEventListener('scroll', handleScroll); return () => { window.removeEventListener('scroll', handleScroll); }; }, []); useEffect(() => { const header = document.getElementById('header'); // Replace 'header' with the ID of your header element // Add/remove scroll direction class if (scrollDirection === 'down') { header?.classList.add('scroll-down'); header?.classList.remove('scroll-up'); console.log(scrollDirection) } else { header?.classList.remove('scroll-down'); header?.classList.add('scroll-up'); console.log(scrollDirection) } }, [scrollDirection]); return null; }; export default ScrollAwareHeader;