# Silky Smooth Scrolling in ReactJS: A Step-by-Step Guide for React Developers

> Learn how to implement smooth scrolling in React JS with react-smoothscroll library. Improve user experience and keep visitors engaged with seamless scrolling.

- **Source:** DevDreaming (https://devdreaming.com)
- **Canonical URL:** https://devdreaming.com/blogs/smooth-scrolling-in-react-js
- **Author:** CodeBucks
- **Published:** 2021-09-13
- **Last updated:** 2023-01-29
- **Topics:** UI Design, React js

---

Hi There 👋,

In this tutorial we're going to implement smooth🧈 scrolling effect🤩 for whole page with custom scrollbar in [React JS](/).
Here is the demo link👇
[Smooth scrolling in React.js](https://react-smooth-scroll.vercel.app/)
(This might load slower initially due to loading of lot's of images)

Before we start, if you prefer the video format then here is the video tutorial👇

[▶ Watch the video on YouTube](https://www.youtube.com/watch?v=x5yvDlH7X9A)

If you're not the beginner and want to implement smooth scrolling in your project
you can directly go to the **Add random Images** section.

### Setting Up The environment

Open your command prompt and create your project directory using following command.

```powershell
npx create-react-app react-smoothscroll
```

> Create React App (
>
> [CRA](https://create-react-app.dev/)
>
> ) is an officially supported way to create single-page
>
> [React applications](/videos/category/web-app)
>
> . It offers a modern build setup with no configuration.

This will create a React app starter and install all the required dependencies for React. For this project we're going to use [smooth-scrollbar](https://idiotwu.github.io/smooth-scrollbar/), So let's install it,

```powershell
npm install smooth-scrollbar
```

Now let's start our project server by using the following command,

```powershell
npm start
```

This will start the server on port 3000.

### Adding Fake Data On Page

First of all clean up your `App.js` file and remove the `header` section. Now before implementing smooth scroll, we need some content to display in the app. For this we can render few images one by one. You can obtain various images from [picsum-photos](https://picsum.photos/). Go to given url and scroll down to [list images](https://picsum.photos/v2/list). Now let's call this url and render a few images. Open `App.js` file and write following code👇

```javascript
import { useEffect, useState } from 'react';

import './App.css';

function App() {
const [images, setImages] = useState();

  useEffect(() => {

      fetch('https://picsum.photos/v2/list?limit=10').then(res =>  res.json())
      .then(json => {
        console.log(json);
        setImages(json);
      });

 }, [])

  const random = () => {

    return Math.floor(Math.random()*50);

  }

  return (

    <div className="App">
      <h1 className="title">React Smooth Scroll</h1>
      {
        images && images.map(
          img => <div style={{marginLeft: `${random()}rem` }} key={img.id} className="imgContainer">
            <img   src={img.download_url} alt={img.author} />
          </div>
        )
      }
    </div>

  );
}

export default App;
```

**Line no:6** Here We have initialized a state `images` to store images.

**Line no:8** In the `useEffect` We have fetched the url which provides us image data in JSON format. After converting response (res) to JSON we will set `images` state with this JSON data.

Here is the Format of JSON data:

```json
[
  {
    "id": "0",
    "author": "Alejandro Escamilla",
    "width": 5616,
    "height": 3744,
    "url": "https://unsplash.com/...",
    "download_url": "https://picsum.photos/..."
  }
]
```

**Line no:25** In the return statement, we will render images when `images` state is not undefined using map function. Here all images are wrapped inside the `div` with the class `imgContainer` .

> To keep images scattered on the whole page I have used random function to set it's margin randomly. (As you saw in the demo page)

**Line no:27** Here, We have to pass `download_url` in the src and pass author in the alt tag. Let's write following code for the css in the `App.css` file.

```css
. App {
display:flex;
flex-direction: column;
padding:5rem;
}

.title{
  text-transform: uppercase;
  align-self: center;
  margin-bottom:8rem;
  font-size:4vw;
}

.imgContainer{
  max-width:50vw;
  margin:4rem 0;
}

img{
  width:100%;
  height:auto;
}
```

### Implementing smooth scrolling

Let's create `components` folder in the `src` folder and create one file called `SmoothScroll.js` inside that folder. Let's add the following code in the `SmoothScroll.js` file.

```javascript
const Scroll = () => {
  return null;
};

export default Scroll;
```

Let's import scrollbar from `smooth-scrollbar` .

```javascript
import Scrollbar from "smooth-scrollbar";
```

Let's initialize it in the useEffect using the following syntax.

```javascript
Scrollbar.init(document.querySelector("#my-scrollbar"), options);
```

In the `init` function pass the element where you want to implement smooth scrolling and in the second argument you can pass various options which are listed in the [documentation of smooth-scrollbar](https://github.com/idiotWu/smooth-scrollbar/tree/49f4ee4543019cf65a6107e092f834a247c2652c/docs#available-options-for-scrollbar). You can also try different options in this [live demo of smooth scrolling](https://idiotwu.github.io/smooth-scrollbar/). Now Let's Add this in the `Scroll` component.

```javascript
const options = {
  damping: 0.07,
};

useEffect(() => {
  Scrollbar.init(document.body, options);

  return () => {
    if (Scrollbar) Scrollbar.destroy(document.body);
  };
}, []);
```

In the `useEffect` , we want to create smooth scrolling in the whole page so pass `document.body` in the first argument While, in the second argument pass `options` which we have defined already. In the return of `useEffect` ,
when component unmounts we will destroy the Scrollbar instance using `destroy()` method. Let's import `Scroll` component in the `App.js` file as shown the following code,

```javascript
...
return (
  <div className="App">
    <h1 className="title">React Smooth Scroll</h1>
    <Scroll /> {/*👈 Like this*/}
...
```

Now we have to set `height` and `width` of the body otherwise this will not work. Open `index.css` file and let's add height and width in the body.

```css
body {
  margin: 0;
  height: 100vh;
  width: 100vw;
}
```

You should see the smooth scrolling effect after adding the above `css` .

### Customizing `smooth-scrollbar` Using Overscroll Plugin

Now if you want any effect of glow or bounce when someone hit the scroll ends, then you can use `Overscroll` plugin. Let's open `SmoothScroll.js` file, and import this plugin from smooth-scrollbar.

```javascript
import OverscrollPlugin from "smooth-scrollbar/plugins/overscroll";
```

Checkout the following code and it's explanation.

```javascript
import Scrollbar from 'smooth-scrollbar';
import { useEffect } from 'react';
import OverscrollPlugin from 'smooth-scrollbar/plugins/overscroll';

const overscrollOptions = {
  enable: true,
  effect: 'bounce',
  damping: 0.15,
  maxOverscroll: 150,
  glowColor: '#fff',
};

//   const overscrollOptions = {
//     enable: true,
//     effect: 'glow',
//     damping: 0.1,
//     maxOverscroll: 200,
//     glowColor: '#222a2d',
//   };

const options = {
  damping : 0.07,
  plugins: {

    overscroll: { ...overscrollOptions },

  },
}

const Scroll = () => {

  useEffect(() => {

    Scrollbar.use(OverscrollPlugin);
    Scrollbar.init(document.body, options);

    return () => {
      if (Scrollbar) Scrollbar.destroy(document.body)
    }  },[])

  return null;
}

export default Scroll;
```

**Line no:5**: Here are `Overscroll` plugin options.

**Line no:24**: We have added `Overscroll` plugin and it's options in the main `options` object.

**Line no:32**: Here we have used `Scrollbar.use()` method to use `Overscroll` plugin.

That's it. Now you should see smooth bounce when scrollbar hits the ends.

> If you want to implement glow effect just uncomment the code from the
>
> **line no 16**
>
>  and comment out the current overscroll options.

You can use various methods provided by this library from it's [documentation](https://github.com/idiotWu/smooth-scrollbar/blob/49f4ee4543019cf65a6107e092f834a247c2652c/docs/api.md#table-of-contents). That's the end of this article hope you like it💛.

---

## Related on DevDreaming

- [All Blog Posts](https://devdreaming.com/blogs)
- [Free Developer Tools](https://devdreaming.com/tools)
- [Video Tutorials](https://devdreaming.com/videos)
- [AI Tools for Developers](https://devdreaming.com/ai-tools)

---

_This is the Markdown twin of a page on **DevDreaming** -- free developer tutorials, tools, and AI resources. Source of truth: the canonical HTML URL above._