Home >Web Front-end >JS Tutorial >How to Scroll to an Element in React?
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:
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> </> ); };
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 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. }
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!