Scroll to a component on click on in React

Scroll to a component on click on in React #

To scroll to a component on click on in React:

  1. Set a ref prop at the part you need to scroll to.
  2. Set the onClick prop at a different part.
  3. Each time the part is clicked, name the scrollIntoView() approach at the
    ref object.
import {useRef} from 'react';

export default serve as App() {
  const ref = useRef(null);

  const handleClick = () => {
    ref.present?.scrollIntoView({conduct: 'clean'});
  };

  go back (
    <div>
      <button onClick={handleClick}>Scroll to part</button>

      <div taste={{top: '155rem'}} />

      <div ref={ref}>Some content material right here</div>

      <div taste={{top: '155rem'}} />
    </div>
  );
}

We initialized a ref for the usage of the
useRef hook.

The useRef() the hook will also be handed a preliminary worth as a controversy. The hook
returns a mutable ref object whose .present belongings are initialized to the
handed argument.

Understand that we need to get the right of entry to the present belongings at the ref object to get right of entry to the div the part on which we set the ref prop.

After we cross a ref prop to a component, e.g. <div ref={myRef} />, React units
the .present belongings of the ref object to the corresponding DOM node.

We set the onClick prop at the button part, so each and every time it is clicked, the
handleClick serve as is invoked.

const handleClick = () => {
  ref.present?.scrollIntoView({conduct: 'clean'});
};

Within the handleClick serve as, we used the
scrollIntoView
strategy to scroll to the div part on which the ref prop is about.

The conduct belongings specifies whether or not the scrolling will have to animate easily (clean), or occur immediately (auto).

The default worth for the conduct belongings is auto.

Each time the button is clicked, the scrollIntoView() approach is invoked on
the part on which we set the ref prop, and the part is made visual to
the consumer.

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