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 .
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> </> ); };
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 }
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 }
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!