Sticky element on a scroll in React

If you want to add a sticky div or paragraph on page scroll then today we will show you how to add a sticky element on a scroll in React. Here, we will not use any NPM Package to achieve this functionality.

Output

For demostration, we will add the sticky sidebar on page scroll.

Output - Sticky element on a scroll in React - Clue Mediator
Output – Sticky element on a scroll in React – Clue Mediator

Steps to add a sticky element on a scroll

  1. Create a react application
  2. Add a listener for the sticky element
  3. Output

1. Create a react application

Let’s create a React application using the create-react-app and render a component that contains the sidebar along with the content.

App.js

2. Add a listener for the sticky element

In the next step, we will add a listener for the sticky element. On page scroll, we will add/remove is-sticky class to the sidebar.

Add the following CSS.

index.css

3. Output

Let’s put all the code together and see how it looks.

App.js

Run the application and check the output in the browser.

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

2 Responses

  1. Hafiz Aslam says:

    It is giving me error
    Uncaught (in promise) TypeError: Cannot read properties of null (reading ‘getBoundingClientRect’)

Leave a Reply

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