Home > Web Front-end > JS Tutorial > body text

How to Scroll to an Element in React?

Linda Hamilton
Release: 2024-11-14 09:37:02
Original
807 people have browsed it

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>
    </>
  );
};
Copy after login

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.
}
Copy after login

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.
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template