In this tutorial, we will discuss how to implement the On Scroll event handler in React Js application to implement fixed top header. We will deploy the useLayoutEffect hook of functional components to freeze the header content.
The fixed header is used to display the application branding or other content in the same place even if the user scrolls the content. A sticky header is usually placed at the top of a website or application.
To implement the onScroll event in React Js we will use the useLayoutEffect hook of functional components.
How to use OnScroll Event in React JS Create Fixed Header
Step 1 – Create React Application
Step 2 – Make FixedHeader Component
Step 3 – Add Sticky Header Style
Step 4 – Import FixedHeader Component
Step 5 – See In Action
Step 1 – Create React Application
First, make sure you have installed the create react app in your system:
npm install create-react-app --global
Next, you can create a new React js application by executing the below npx command:
npx create-react-app react-app
Thereafter move into the app directory and open in your favourite IDE like VS Code:
cd react-app
code .
Step 2 – Make FixedHeader Component
Now head towards the src folder and create a components folder with a file named Fixedheader.js
Update the src/components/Fixedheader.js file with the following code in it:
import React, { useRef, useLayoutEffect } from "react";
function Fixedheader() {
const stickyHeader = useRef();
useLayoutEffect(() => {
const topHeader = document.getElementById("topHeader");
let fixedTop = stickyHeader.current.offsetTop;
const fixedHeader = () => {
if (window.pageYOffset > fixedTop) {
topHeader.classList.add("fixedTop");
} else {
topHeader.classList.remove("fixedTop");
}
};
window.addEventListener("scroll", fixedHeader);
}, []);
return (
<div>
<div className="topHeader" id="topHeader" ref={stickyHeader}>
<h2>React Fixed Header</h2>
</div>
<div className="content-wrapper">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Vel risus
commodo viverra maecenas. Non blandit massa enim nec dui nunc. Aliquet
lectus proin nibh nisl condimentum id venenatis a condimentum. Cursus
euismod quis viverra nibh cras pulvinar mattis. Consectetur a erat nam
at lectus urna duis. Magna etiam tempor orci eu lobortis elementum
nibh. Nam libero justo laoreet sit amet cursus sit amet. Dignissim
diam quis enim lobortis scelerisque fermentum dui. Sagittis aliquam
malesuada bibendum arcu vitae elementum curabitur vitae nunc.
</p>
<p>
Malesuada bibendum arcu vitae elementum curabitur vitae nunc sed
velit. Ac ut consequat semper viverra nam libero justo laoreet.
Sodales ut eu sem integer vitae justo eget magna. Velit sed
ullamcorper morbi tincidunt ornare. Nibh nisl condimentum id venenatis
a. Dignissim cras tincidunt lobortis feugiat vivamus at augue eget
arcu. Eu turpis egestas pretium aenean pharetra magna. Tellus integer
feugiat scelerisque varius morbi enim nunc faucibus a. Mauris ultrices
eros in cursus turpis massa. Sit amet cursus sit amet dictum sit amet.
Id faucibus nisl tincidunt eget nullam.
</p>
<p>
Lobortis scelerisque fermentum dui faucibus in ornare quam viverra.
Eget lorem dolor sed viverra. Sit amet nulla facilisi morbi tempus
iaculis urna id volutpat. Nibh cras pulvinar mattis nunc sed blandit
libero volutpat. Purus in mollis nunc sed. Et netus et malesuada
fames. Sit amet mattis vulputate enim nulla aliquet porttitor lacus.
Sem fringilla ut morbi tincidunt augue interdum. Risus commodo viverra
maecenas accumsan lacus vel facilisis volutpat est. Metus aliquam
eleifend mi in nulla posuere sollicitudin aliquam. Adipiscing
tristique risus nec feugiat in fermentum posuere urna. Habitant morbi
tristique senectus et netus. Id aliquet risus feugiat in ante. Viverra
nibh cras pulvinar mattis.
</p>
<p>
Varius morbi enim nunc faucibus. A condimentum vitae sapien
pellentesque habitant morbi tristique senectus et. Elementum integer
enim neque volutpat ac tincidunt. Accumsan in nisl nisi scelerisque eu
ultrices. Arcu felis bibendum ut tristique et. Nulla at volutpat diam
ut venenatis tellus in. Sit amet porttitor eget dolor morbi non arcu.
Volutpat ac tincidunt vitae semper quis lectus nulla. Diam vulputate
ut pharetra sit amet aliquam id diam. Tristique nulla aliquet enim
tortor. Platea dictumst quisque sagittis purus. Tortor consequat id
porta nibh. Volutpat odio facilisis mauris sit amet massa vitae
tortor.
</p>
<p>
Rhoncus urna neque viverra justo nec ultrices dui. Morbi tristique
senectus et netus et malesuada fames ac. Ultrices neque ornare aenean
euismod elementum nisi quis. Massa placerat duis ultricies lacus sed.
Et malesuada fames ac turpis egestas integer eget aliquet nibh. Amet
consectetur adipiscing elit ut. Convallis posuere morbi leo urna
molestie. Volutpat blandit aliquam etiam erat velit scelerisque in
dictum non. Viverra nam libero justo laoreet sit amet cursus. Orci eu
lobortis elementum nibh. Magnis dis parturient montes nascetur
ridiculus mus mauris vitae ultricies.
</p>
</div>
</div>
);
}
export default Fixedheader;
We are taking the reference of the element with id=”mainHeader” then getting the offsetTop using the ‘scroll’ event bound to the window object.
Why deploy useLayoutEffect()
hook?
The important thing to notice that ‘scroll’ event return error message “Cannot read property ‘offsetTop’ of null” because the id=’mainHeader’ element is not yet rendered inside the DOM.
To fix this we need to execute the window ‘scroll’ event handler inside the useLayoutEffect
hook. This hook is executed only after the complete DOM is rendered in the view to get the offsetTop value.
Step 3 – Add Sticky Header Style
The sticky header feature is implemented by adding a custom class ‘fixedTop’ on checking if user scroll to the bottom or at the top. So we will be adding the following CSS style to freeze out fixed header.
Open the App.css file and append following style in it:
.topHeader {
padding: 12px 18px;
background: rgb(0 0 0);
color: #fff;
text-align: center;
}
.content-wrapper {
padding: 16px;
max-width: 900px;
margin: 0 auto;
font-size: 18px;
}
.fixedTop {
width: 100%;
padding: 12px 18px;
position: fixed;
top: 0;
background: rgb(255 226 0);
}
.fixedTop+.content-wrapper {
padding-top: 102px;
}
Step 4 – Import FixedHeader Component
Finally, we need to import the FixedHeader component in the main App component. Update the App.js file with following code:
import "./App.css";
import React from "react";
import Fixedheader from "./components/Fixedheader";
function App() {
return (
<div>
<Fixedheader />
</div>
);
}
export default App;
Step 5 – See In Action
Now, you can run the React js application to see the Sticky Header in action.
npm start
It will start the local webserver to deploy your application at following URL:
Conclusion
We discussed how to add a OnScroll event handler in React js application. Using the useLayoutEffect hook available in functional components we can bind the OnScroll event on elements without facing any issues.
The OnScroll event can be used to implement various similar kind functionalities like adding frozen footer bar or getting a dynamic Offset top of the page on scroll.