Home  >  Article  >  Web Front-end  >  How to Scroll to an Element in React?

How to Scroll to an Element in React?

Linda Hamilton
Linda HamiltonOriginal
2024-11-14 09:37:02808browse

How to Scroll to an Element in React?

How to scroll to an element?

You want your chat widget to automatically focus on the last message when new messages are loaded. To achieve this, you need to create a dynamic reference for each message and use a scroll function to scroll to the last element.

Here's how you can do it:

React 16.8 , Functional component

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

  const executeScroll = () => myRef.current.scrollIntoView(); // run this function from an event handler or an effect to execute scroll

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

React 16.3 , Class component

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(); // run this method to execute scrolling.
}

Class component - Ref callback

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

  executeScroll = () => this.myRef.scrollIntoView(); // run this method to execute scrolling.
}

Notes:

  • Avoid using string refs as they are deprecated.
  • Pass ref to the DOM element, not to the React component.
  • Add CSS to enable smooth scroll animation.

The above is the detailed content of How to Scroll to an Element 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