Home >Web Front-end >JS Tutorial >How to Scroll to the Bottom of a Chat Widget in React?
In this article, we'll address a common issue where a chat widget's scrollbar remains fixed at the top when new messages load. Our goal is to focus the scrollbar on the last message element from the previous array.
To solve this issue, we need to:
React 16.8 , Functional Component:
const ScrollDemo = () => { const myRef = useRef(null); const executeScroll = () => myRef.current.scrollIntoView(); // Scroll to the element 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(); // Scroll to the element }
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(); // Scroll to the element }
Important Notes:
html { scroll-behavior: smooth; }
The above is the detailed content of How to Scroll to the Bottom of a Chat Widget in React?. For more information, please follow other related articles on the PHP Chinese website!