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 (
	  header === "header1" ? <HeaderOne/>
		  : header === 'header2' ?
			  : header === 'header3' ?
				  : null


react 6270864605519753665

Post a Comment Default Comments

1 comment

zavannahjacin said...
This comment has been removed by a blog administrator.


Are you looking for freelancers in the Philippines? Get in touch.


If you like what I do, you can support this channel by buying me a coffee. I would be grateful for your contribution! Your donations will help me create more FREE online courses and learning materials for programmers and remote workers.