Home//

How to Show and Hide a React Component on Scroll

How to Show and Hide a React Component on Scroll

Minh Vu

By Minh Vu

Updated Jul 15, 2023

In this tutorial, we will learn how to show and hide a React component based on the user's scroll position. This can be useful in various scenarios, such as displaying a navigation bar when the user scrolls up or showing a "Back to Top" button when the user scrolls down. We will explore different examples to demonstrate the flexibility of this technique.

Example 1: Show a React Component When User Scrolls Up

Let's start with a simple example of showing a React component when the user scrolls up. We will create a navigation bar that is initially hidden and only becomes visible when the user scrolls up.

First, let's create a new React component called ScrollUpNav:

import React, { useState, useEffect } from "react"; const ScrollUpNav = () => { const [isVisible, setIsVisible] = useState(false); const [prevScrollPos, setPrevScrollPos] = useState(window.pageYOffset); useEffect(() => { const handleScroll = () => { const currentScrollPos = window.pageYOffset; setIsVisible(prevScrollPos > currentScrollPos); setPrevScrollPos(currentScrollPos); }; window.addEventListener("scroll", handleScroll); return () => window.removeEventListener("scroll", handleScroll); }, [prevScrollPos]); return ( <nav className={`scroll-up-nav ${isVisible ? "visible" : ""}`}> {/* Navigation content */} </nav> ); }; export default ScrollUpNav;

In this component, we use the useState hook to manage the visibility state of the navigation bar. The isVisible state is initially set to false. We also use the prevScrollPos state to keep track of the previous scroll position.

Inside the useEffect hook, we add an event listener to the scroll event. Whenever the user scrolls, the handleScroll function is called. Inside this function, we compare the current scroll position (window.pageYOffset) with the previous scroll position (prevScrollPos). If the user has scrolled up (i.e., the current scroll position is smaller than the previous scroll position), we set isVisible to true. Otherwise, we set it to false. We also update the prevScrollPos with the current scroll position.

Finally, we render the navigation bar (<nav>) with the visible class when isVisible is true.

To use this component in your application, simply import it and place it where you want it to be rendered:

import ScrollUpNav from "./ScrollUpNav"; const App = () => { return ( <div> <h1>Welcome to My Website</h1> <ScrollUpNav /> {/* Rest of the app */} </div> ); }; export default App;

Now, when the user scrolls up, the navigation bar will become visible. You can style the navigation bar using CSS to achieve the desired look and feel.

Example 2: Show a React Component When User Scrolls Down

Next, let's explore an example of showing a React component when the user scrolls down. We will create a "Back to Top" button that is initially hidden and only appears when the user scrolls down.

Similar to the previous example, we will create a new React component called ScrollDownButton:

import React, { useState, useEffect } from "react"; const ScrollDownButton = () => { const [isVisible, setIsVisible] = useState(false); const [prevScrollPos, setPrevScrollPos] = useState(window.pageYOffset); useEffect(() => { const handleScroll = () => { const currentScrollPos = window.pageYOffset; setIsVisible(prevScrollPos < currentScrollPos); setPrevScrollPos(currentScrollPos); }; window.addEventListener("scroll", handleScroll); return () => window.removeEventListener("scroll", handleScroll); }, [prevScrollPos]); const scrollToTop = () => { window.scrollTo({ top: 0, behavior: "smooth", }); }; return ( <button className={`scroll-down-button ${isVisible ? "visible" : ""}`} onClick={scrollToTop} > Back to Top </button> ); }; export default ScrollDownButton;

In this component, we use the same approach as before to manage the visibility state (isVisible) and the previous scroll position (prevScrollPos).

Inside the useEffect hook, we compare the current scroll position with the previous scroll position. If the user has scrolled down (i.e., the current scroll position is greater than the previous scroll position), we set isVisible to true. Otherwise, we set it to false.

We also add a scrollToTop function that is called when the button is clicked. This function uses the window.scrollTo method to smoothly scroll to the top of the page.

Finally, we render the "Back to Top" button (<button>) with the visible class when isVisible is true.

To use this component in your application, import it and place it where you want it to be rendered:

import ScrollDownButton from "./ScrollDownButton"; const App = () => { return ( <div> <h1>Welcome to My Website</h1> {/* Rest of the app */} <ScrollDownButton /> </div> ); }; export default App;

Now, when the user scrolls down, the "Back to Top" button will appear. Clicking on the button will smoothly scroll the page to the top.

Example 3: Show and Hide Multiple React Components on Scroll

In some cases, you may want to show and hide multiple React components based on the user's scroll position. Let's explore an example where we have two components: a header and a footer. The header should be visible when the user scrolls up, and the footer should be visible when the user scrolls down.

First, let's create a new React component called ScrollHeaderFooter:

import React, { useState, useEffect } from "react"; const ScrollHeaderFooter = () => { const [isHeaderVisible, setIsHeaderVisible] = useState(false); const [isFooterVisible, setIsFooterVisible] = useState(false); const [prevScrollPos, setPrevScrollPos] = useState(window.pageYOffset); useEffect(() => { const handleScroll = () => { const currentScrollPos = window.pageYOffset; setIsHeaderVisible(prevScrollPos > currentScrollPos); setIsFooterVisible(prevScrollPos < currentScrollPos); setPrevScrollPos(currentScrollPos); }; window.addEventListener("scroll", handleScroll); return () => window.removeEventListener("scroll", handleScroll); }, [prevScrollPos]); return ( <div> <header className={`scroll-header ${isHeaderVisible ? "visible" : ""}`}> {/* Header content */} </header> {/* Rest of the app */} <footer className={`scroll-footer ${isFooterVisible ? "visible" : ""}`}> {/* Footer content */} </footer> </div> ); }; export default ScrollHeaderFooter;

In this component, we introduce two new states: isHeaderVisible and isFooterVisible. These states control the visibility of the header and footer components, respectively.

Inside the useEffect hook, we compare the current scroll position with the previous scroll position. If the user has scrolled up, we set isHeaderVisible to true and isFooterVisible to false. If the user has scrolled down, we set isHeaderVisible to false and isFooterVisible to true.

We render the header (<header>) and footer (<footer>) components with the visible class when their respective visibility states are true.

To use this component in your application, import it and place it where you want it to be rendered:

import ScrollHeaderFooter from "./ScrollHeaderFooter"; const App = () => { return ( <div> <ScrollHeaderFooter /> {/* Rest of the app */} </div> ); }; export default App;

Now, when the user scrolls up, the header will become visible, and when the user scrolls down, the footer will become visible.

  • React Scroll: A library for smooth scrolling in React applications.
  • React Intersection Observer: A React wrapper for the Intersection Observer API, which can be used to detect when an element enters or exits the viewport.
  • Scroll Event: MDN Web Docs on the scroll event and how to use it.

In this tutorial, we have learned how to show and hide a React component based on the user's scroll position. We explored different examples, including showing a component when the user scrolls up, showing a component when the user scrolls down, and showing and hiding multiple components on scroll. By using the techniques demonstrated in this tutorial, you can create dynamic and interactive user experiences in your React applications.

Remember to experiment with different styles and animations to make your components stand out. Happy coding!

You can search for other posts at home page.
Minh Vu

Minh Vu

Software Engineer

Hi guys, I'm the author of WiseCode Blog. I mainly work with the Elastic Stack and build AI & Python projects. I also love writing technical articles, hope you guys have good experience reading my blog!