Animated sticky header on scroll in React

Today we’ll show you how to create an animated sticky header on scroll in React JS without plugin. While you are working with react applications, it’s good practice to do not manipulate the real dom by injecting the JavaScript but we can manage it in a different way by using Refs. So the same concept we will use in this demo.

Building a sticky header component in React, Build a sticky navigation bar with React, Simple sticky/fixed header that animates on scroll, React Sticky Header Elements Component on Scroll in React, Building an animated sticky header with custom offset, How I linked animated headers to scroll position in React, react-sticky navbar on scroll, bootstrap sticky header on scroll.

In a previous article we have explained how to create sticky header on page scroll in JavaScript where we wrote a custom script to stick a header. Now in this article we will use useRef & useEffect to manage the sticky header using React Hooks. Let’s take an example.

Steps to create an animated sticky header on scroll

  1. Create a sample website in React
  2. Implement react code for sticky header
  3. Output

1. Create a sample website in React

Let’s set up a simple react application using create-react-app and create a sample website by adding the below HTML and CSS in app.

app.js

index.css

2. Implement react code for sticky header

Now we will initialize the state object and header reference. State objects will have two variables, the one used to enable the sticky header and the other used to set the margin of the component when we fix the header. Header reference will be used to access the real dom node. Check the following code.

Let’s create a scroll event handler that will be used to observe the window scroll position and compare it with header top offset and height.

Use the above function to add on scroll event listeners. Also we have to remove it when the component will unmount.

In the above function, we have created one more function to pass in the event listener because otherwise it will not be removed on unmount.

Finally let’s use headerRef and offset to complete the example.

3. Output

Let’s combine all code together and see the output.

app.js

Output - Animated sticky header on scroll in React - Clue Mediator
Output – Animated sticky header on scroll in React – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *