How to Create Sticky Header with OnScroll Handler in React

In this guide, we will find out how to create a sticky header in React js application using the function component and the useLayoutEffect hook.

The sticky header fixes itself to the top position when it is scrolled passed and remains attached to the viewport.

The term sticky is essential for certain digital products as it enhances user engagement and lets the users spend more time surfing through their digital products.

A sticky header is used when it is required for the users to show something fundamental. It could be a navigation bar, categories, etc.; Facebook and Twitter are the best examples of sticky headers.

React On Scroll Fixed and Sticky Header Tutorial

  • Step 1: Download React Project
  • Step 2: Create New Component
  • Step 3: Implement Fixed Header in React
  • Step 4: Update Global Component
  • Step 5: Add CSS to Sticky Header
  • Step 6: Run React Application

Download React Project

You have to open the terminal, type the given command and execute command to install the react app.

npx create-react-app react-blog

You can get inside the project folder with below command.

cd react-blog

Create New Component

We need a components/ folder with Home.js file located into it, this is going to be the basic component for sticky header feature.

import React from 'react'

function Home() {
  return (
    <div>Home</div>
  )
}

export default Home

Implement Fixed Header in React

Head over to the components/Home.js file, and write the given code into the file.

import React, { useLayoutEffect, useRef } from 'react'

function Home() {
  const headerRef = useRef()

  useLayoutEffect(() => {
    const header = document.getElementById('header')

    let fixedTop = headerRef.current.offsetTop

    const stickyTop = () => {
      if (window.pageYOffset > fixedTop) {
        header.classList.add('sticky')
      } else {
        header.classList.remove('sticky')
      }
    }
    window.addEventListener('scroll', stickyTop)
  }, [])

  return (
    <div>
      <div className="header" id="header" ref={headerRef}>
        <h2>React Js onScroll Sticky Header Example</h2>
      </div>
      <div className="container">
        <p>
          Sed imperdiet id lacus at volutpat. Vivamus id ipsum a arcu
          pellentesque iaculis venenatis nec justo.
        </p>
        <p>
          Sed imperdiet id lacus at volutpat. Vivamus id ipsum a arcu
          pellentesque iaculis venenatis nec justo.
        </p>
        <p>
          Sed imperdiet id lacus at volutpat. Vivamus id ipsum a arcu
          pellentesque iaculis venenatis nec justo.
        </p>
        <p>
          Sed imperdiet id lacus at volutpat. Vivamus id ipsum a arcu
          pellentesque iaculis venenatis nec justo.
        </p>
        <p>
          Sed imperdiet id lacus at volutpat. Vivamus id ipsum a arcu
          pellentesque iaculis venenatis nec justo.
        </p>
        <p>
          Sed imperdiet id lacus at volutpat. Vivamus id ipsum a arcu
          pellentesque iaculis venenatis nec justo.
        </p>
        <p>
          Sed imperdiet id lacus at volutpat. Vivamus id ipsum a arcu
          pellentesque iaculis venenatis nec justo.
        </p>
        <p>
          Sed imperdiet id lacus at volutpat. Vivamus id ipsum a arcu
          pellentesque iaculis venenatis nec justo.
        </p>
        <p>
          Sed imperdiet id lacus at volutpat. Vivamus id ipsum a arcu
          pellentesque iaculis venenatis nec justo.
        </p>
        <p>
          Sed imperdiet id lacus at volutpat. Vivamus id ipsum a arcu
          pellentesque iaculis venenatis nec justo.
        </p>
        <p>
          Sed imperdiet id lacus at volutpat. Vivamus id ipsum a arcu
          pellentesque iaculis venenatis nec justo.
        </p>
        <p>
          Sed imperdiet id lacus at volutpat. Vivamus id ipsum a arcu
          pellentesque iaculis venenatis nec justo.
        </p>
        <p>
          Sed imperdiet id lacus at volutpat. Vivamus id ipsum a arcu
          pellentesque iaculis venenatis nec justo.
        </p>
      </div>
    </div>
  )
}

export default Home

Add CSS to Sticky Header

Open App.css file, in this file we will start writing some css, it will be used for a basic layout.

.header {
  padding: 15px 20px;
  text-align: center;
  color: #fff;
  background: rgb(7, 1, 33);
}

.container {
  padding: 18px;
  width: 900px;
  margin: 0 auto;
  font-size: 20px;
}

.sticky {
  top: 0;
  width: 900px;
  padding: 15px 20px;
  position: fixed;
  background: rgb(249, 57, 9);
}

.sticky + .container {
  padding-top: 105px;
}

Update Global Component

We have created the Home component, now that component needs to be added to the App.js component file.

import React from 'react'
import './App.css'
import Home from './components/Home'

function App() {
  return (
    <div>
      <Home />
    </div>
  )
}

export default App

Run React Application

In the last step, we will use the following command and run it to start the react app.

npm start

We can now use this url to test the app.

http://localhost:3000

How to Create Sticky Header in React On Scroll Event Handler

Summary

To create the sticky header, we created a simple component and imported the useRef and useLayoutEffect hooks.

Get the header offset position, write a simple function that calculates if the page y offset is greater than the header element, and bind it to the event listener.