How to display a component on scroll in React
1. Requirement
Display a component depending on the value of window.scrollY. In this example, we are displaying 3 level of header navigations.
2. Use Case
A typical use case would be, when displaying a horizontal navigation component on window scroll event. Take a look at Fiverr.
3. Solution
This code snippet is running on React.
// in your component define a React state const [header, setHeader] = React.useState("header1"); // listen to window scroll event and set the state accordingly // in this example, we're displaying a 3 level header navigations const listenScrollEvent = (event) => { if (window.scrollY < 20) { return setHeader("header1") } else if (window.scrollY > 20 && window.scrollY < 200) { return setHeader("header2") } else if (window.scrollY > 200) { return setHeader("header2") } } // and finally, your React component should return the correct header return ( <Box> { header === "header1" ? <HeaderOne/> : header === 'header2' ? <HeaderTwo/> : header === 'header3' ? <HeaderThree/> : null } </Box> );
Post a Comment