Home >Web Front-end >JS Tutorial >How to Efficiently Scroll to Elements in React?

How to Efficiently Scroll to Elements in React?

Linda Hamilton
Linda HamiltonOriginal
2024-11-19 19:09:03396browse

How to Efficiently Scroll to Elements in React?

Efficiently Scrolling to Elements in React

In this article, we tackle a common challenge faced when managing scroll behavior in React applications: ensuring the scroll focus remains on newly loaded elements. We present different approaches to achieve this, suitable for React 16.3 and 16.8 .

React 16.8 , Functional Component

Utilizing the useRef hook, we create a ref for the desired element. By invoking the scrollIntoView function bound to this ref, we smoothly scroll to that element.

const ScrollDemo = () => {
  const myRef = useRef(null);

  const executeScroll = () => myRef.current.scrollIntoView(); // scroll to element

  return (
    <>
      <div ref={myRef}>Element to scroll to</div>
      <button onClick={executeScroll}>Click to scroll</button>
    </>
  );
};

React 16.3 , Class Component

For class components, we can create a ref with React.createRef(). The executeScroll method invokes the scrollIntoView function on the ref to smoothly scroll to the desired element.

class ReadyToScroll extends Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  render() {
    return <div ref={this.myRef}>Element to scroll to</div>;
  }

  executeScroll = () => this.myRef.current.scrollIntoView(); // scroll to element
}

Ref Callback

Alternatively, we can use a ref callback to attach the ref to an element. This method ensures that the ref is assigned directly to the DOM element without creating an instance variable.

class ReadyToScroll extends Component {
  render() {
    return <div ref={ref => (this.myRef = ref)}>Element to scroll to</div>;
  }

  executeScroll = () => this.myRef.scrollIntoView(); // scroll to element
}

Considerations

  • Avoid String Refs: String refs have performance implications and are discouraged by React.
  • Smooth Scroll Animation: Smooth scrolling can be enabled by adding scroll-behavior: smooth to the html element's CSS.
  • Passing Ref to a Child: When passing a ref to a child component, assign it to a prop with a name other than "ref" to avoid conflicts.

The above is the detailed content of How to Efficiently Scroll to Elements in React?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn