no

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>
);

Related

react 6270864605519753665

Post a Comment Default Comments

1 comment

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

Outsourcing

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

Donations

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.

item