Find out how to Scroll to Part in React

Scrolling to a component in React will also be accomplished the usage of undeniable JavaScript.

You’ll make a choice a DOM part and replace the scrollable part’s (e.g. frame) scrollTop place manually, or the usage of the scrollTo way to fit the DOM part’s most sensible place at the display. On the other hand, there may be an more uncomplicated means…

The most straightforward approach to scroll to a component in React is through calling the scrollIntoView serve as at the part. On the other hand, you first want to get the DOM part ref from useRef or make a choice it from the DOM at once.

Here is how chances are you’ll scroll to every other part when clicking a button:

import './taste.css';

serve as BasicExample() {
  const handleClickScroll = () => {
    const part = record.getElementById('section-1');
    if (part) {
      // ? Will scroll easily to the highest of the following part
      part.scrollIntoView({ habits: 'clean' });
    }
  };

  go back (
    <>
      <div identification="hero-section">
        <button className="btn-scroll" onClick={handleClickScroll}>
          Scroll Down
        </button>
      </div>
      <div identification="section-1">Segment 1</div>
    </>
  );
}

export default BasicExample;
Elementary instance of scrollIntoView utilization in React

Moreover, the scrollIntoView means accepts non-compulsory parameters to keep an eye on the scroll animation and the place to concentrate on the part.

Scroll to a brand new part in React

As a result of we require a referent to a DOM part to scroll it into view, we would possibly run into issues when the DOM part is created in accordance with state adjustments in React.

An instance of this downside is an inventory, the place we need to scroll to the closing part within the listing after a brand new one is added, however the listing is rendered in line with an array within the state.

If we attempt to straight away scroll all the way down to the closing part on the backside, we would be off through one since the new DOM part is not but rendered in line with the up to date state.

You’ll use the flushSync means from react-dom to replace the DOM straight away after the part state is up to date. Here is how it may be used:

import { useRef, useState } from 'react';
import { flushSync } from 'react-dom';
import { v4 as uuid } from 'uuid';
import { uniqueNamesGenerator, names } from 'unique-names-generator';
import './taste.css';

kind Individual = {
  identification: string;
  identify: string;
};

serve as Instance() {
  const listRef = useRef<HTMLUListElement | null>(null);
  const [people, setPeople] = useState<Individual[]>([]);

  const handleAddClick = () => {
    // ? Will wait till the DOM is up to date with the brand new state
    flushSync(() => {
      setPeople((other folks) => [
        ...people,
        {
          id: uuid(),
          name: uniqueNamesGenerator({
            dictionaries: [names],
          }),
        },
      ]);
    });

    // ? Scroll to the closing part within the listing
    listRef.present?.lastElementChild?.scrollIntoView();
  };

  go back (
    <>
      <ul className="listing" ref={listRef}>
        {other folks.map((particular person) => (
          <li key={particular person.identification}>{particular person.identify}</li>
        ))}
      </ul>
      <button onClick={handleAddClick}>Upload new particular person</button>
    </>
  );
}

export default Instance;
The use of flushSync to straight away scroll to backside after a brand new merchandise is added in state.

Scrolling to the newly added part within the listing.

Scroll to part provided that wanted

The scrollIntoView means will scroll even supposing the part is already visual at the display. You would possibly not need it to do anything else if that’s the case. There may be another means with the similar choices known as scrollIntoViewIfNeeded.

The scrollIntoViewIfNeeded possibility remains to be experimental with out excellent fortify on Firefox. To succeed in entire fortify, you’ll be able to use a ponyfill.

Caveat

By means of the usage of scrollIntoView (and in addition scrollTo) with habits: clean you might be leaving it as much as the browser to keep an eye on the animation. Which means that the graceful scrolling would possibly not paintings with some browser or OS settings.

I have spotted, that if I uncheck the “Animate controls and components in home windows” field in my Home windows Efficiency Choices, the graceful scrolling stops running throughout all browsers.

To realize extra keep an eye on it’s possible you’ll use a third celebration scroll-into-view library, which can even provide you with further choices to fine-tune the scroll habits.

Conclusion

JavaScript API provides a easy approach to scroll to a component by the use of scrollIntoView means. On the other hand, it does not be offering numerous fine-grained keep an eye on and depends on browser and OS settings.

In case you are keen to position somewhat extra effort, you’ll be able to use a third celebration library which lets you tweak the settings in your liking. It really works through manually updating the scrollTop place, so it is unaffected through the surroundings settings.

Leave a Comment

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

Let's Get in Touch

Read our customer feedback

Please fill in the form below.


    To top