How to scroll into view in React
Tags: react
Published: 2022-07-20 13:30:15

In this article, we will discuss 2 different ways to scroll into a view in React.

## Project Setup

First, create a react project by running the following command:

```bash
npx create-react-app react-scroll-into-view
```

## Scrolling using pure HTML and CSS

Update the `index.css` with the following styles:

```css
body {
  max-width: 900px;
  margin: 10px auto;
}

.App {
  display: flex;
  justify-content: center;
  flex-direction: column;
}
.section {
  height: 100vh;
}

header {
  display: flex;
  justify-content: center;
}

ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
  display: flex;
  position: fixed;
  top: 0;
  background-color: white;
}
li a {
  padding: 1rem;
  text-decoration: none;
}
```

Now update the `App.js` with the following code:

```jsx
function App() {
  return (
    <div className="App">
      <header>
        <ul>
          <li>
            <a href="#home">Home</a>
          </li>
          <li>
            <a href="#products">Products</a>
          </li>
          <li>
            <a href="#services">Services</a>
          </li>
          <li>
            <a href="#about-us">About Us</a>
          </li>
        </ul>
      </header>
      <div className="section" id="home">
        <h2>Home</h2>
        <p>
          Lorem ipsum dolor, sit amet consectetur adipisicing elit. Harum, unde!
          Nisi officia, placeat, enim quibusdam nostrum similique atque
          accusantium natus sit molestias minima voluptates eos doloribus illum
          ullam, pariatur fugiat? Minima minus aspernatur, quos, explicabo sed
          asperiores, enim officia qui voluptates magnam vero aliquid corrupti?
          Aliquid, est! Expedita tempore impedit fuga eligendi veritatis
          molestiae ipsa nulla! Est aspernatur eius corrupti.
        </p>
      </div>
      <div className="section" id="products">
        <h2>Products</h2>
        <p>
          Lorem ipsum dolor, sit amet consectetur adipisicing elit. Harum, unde!
          Nisi officia, placeat, enim quibusdam nostrum similique atque
          accusantium natus sit molestias minima voluptates eos doloribus illum
          ullam, pariatur fugiat? Minima minus aspernatur, quos, explicabo sed
          asperiores, enim officia qui voluptates magnam vero aliquid corrupti?
          Aliquid, est! Expedita tempore impedit fuga eligendi veritatis
          molestiae ipsa nulla! Est aspernatur eius corrupti.
        </p>
      </div>
      <div className="section" id="services">
        <h2>Services</h2>
        <p>
          Lorem ipsum dolor, sit amet consectetur adipisicing elit. Harum, unde!
          Nisi officia, placeat, enim quibusdam nostrum similique atque
          accusantium natus sit molestias minima voluptates eos doloribus illum
          ullam, pariatur fugiat? Minima minus aspernatur, quos, explicabo sed
          asperiores, enim officia qui voluptates magnam vero aliquid corrupti?
          Aliquid, est! Expedita tempore impedit fuga eligendi veritatis
          molestiae ipsa nulla! Est aspernatur eius corrupti.
        </p>
      </div>
      <div className="section" id="about-us">
        <h2>About Us</h2>
        <p>
          Lorem ipsum dolor, sit amet consectetur adipisicing elit. Harum, unde!
          Nisi officia, placeat, enim quibusdam nostrum similique atque
          accusantium natus sit molestias minima voluptates eos doloribus illum
          ullam, pariatur fugiat? Minima minus aspernatur, quos, explicabo sed
          asperiores, enim officia qui voluptates magnam vero aliquid corrupti?
          Aliquid, est! Expedita tempore impedit fuga eligendi veritatis
          molestiae ipsa nulla! Est aspernatur eius corrupti.
        </p>
      </div>
    </div>
  )
}

export default App
```

As you can see in the code, we have a header with links to 4 different sections. We have given the id of each section as the value of the href attribute (eg: `<a href="#products">Products</a>`). We have also added a height of `100vh` to the sections so that they occupy the entire height of the screen and the scrolling is visible correctly.

Now if you run the app and click on one of the menu items, you will see that you are scrolled into that section. However, you will observe that when you click on the menu, it just jumps into that section. You might want your user to have a nicer experience like a smooth scroll. You can add that by adding the following CSS:

```css
html {
  scroll-behavior: smooth;
}
```

Now if you run the application, you will be able to see smooth scrolling. You can also test the application [here](https://codesandbox.io/s/github/collegewap/scroll-into-view-html-css/tree/main).

> Smooth scrolling is not yet supported in Safari. You can check the browser support details [here](https://caniuse.com/css-scroll-behavior).

## Scrolling using useRef hook

If you do not want to give ids and want to use a reference, you can do that by using the following code:

```jsx
import React, { useRef } from "react"

const App = () => {
  const paraRef = useRef(null)
  const clickHandler = () => {
    paraRef.current &&
      paraRef.current.scrollIntoView({ behavior: "smooth", block: "start" })
  }
  return (
    <div>
      <button onClick={clickHandler}>Scroll to Next para</button>
      <p className="section">
        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Unde eum
        repudiandae ut tempore laudantium, provident labore doloremque sit
        magnam, minima temporibus explicabo voluptatibus cupiditate a culpa
        reprehenderit magni, qui aspernatur! Laborum a iure doloribus, officia
        earum asperiores ut, hic voluptates libero sed consequuntur facere
        itaque natus quisquam! Numquam explicabo sint saepe porro, qui quibusdam
        nam eum minima quasi temporibus. Non?
      </p>
      <p className="section" ref={paraRef}>
        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Unde eum
        repudiandae ut tempore laudantium, provident labore doloremque sit
        magnam, minima temporibus explicabo voluptatibus cupiditate a culpa
        reprehenderit magni, qui aspernatur! Laborum a iure doloribus, officia
        earum asperiores ut, hic voluptates libero sed consequuntur facere
        itaque natus quisquam! Numquam explicabo sint saepe porro, qui quibusdam
        nam eum minima quasi temporibus. Non?
      </p>
      <p className="section">
        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Unde eum
        repudiandae ut tempore laudantium, provident labore doloremque sit
        magnam, minima temporibus explicabo voluptatibus cupiditate a culpa
        reprehenderit magni, qui aspernatur! Laborum a iure doloribus, officia
        earum asperiores ut, hic voluptates libero sed consequuntur facere
        itaque natus quisquam! Numquam explicabo sint saepe porro, qui quibusdam
        nam eum minima quasi temporibus. Non?
      </p>
    </div>
  )
}

export default App
```

Here we have used the `useRef` hook to create a reference to the section to which we want to scroll. When the button is clicked we are calling the [scrollIntoView](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) method of the reference.

In the `block` option, you can specify 'end' to scroll to the end of the section and 'center' to scroll into the center of the section.

You can view a working demo [here](https://codesandbox.io/s/github/collegewap/scroll-into-view-useref/tree/main/).