Home >Web Front-end >JS Tutorial >How to Scroll Automatically to a Specific Element in React?
Problem:
In a chat widget, new messages should automatically scroll into view as the user scrolls up. However, the slider remains fixed at the top when new messages load, making it difficult to see the latest ones.
Solution:
To scroll to a specific element when new messages are added, follow these steps:
const ScrollDemo = () => { const myRef = useRef(null); const executeScroll = () => myRef.current.scrollIntoView(); // Run this function 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 }
Avoid String Refs:
String refs are discouraged due to performance issues, lack of composability, and potential removal in future React releases.
Optional: Smooth Scroll Animation:
For a smooth scrolling experience, add the following CSS to the html element:
html { scroll-behavior: smooth; }
Passing Ref to a Child:
To attach a ref to a specific DOM element within a child component:
const MyComponent = () => { const myRef = useRef(null); return <ChildComp refProp={myRef} />; };
Within the ChildComp component:
const ChildComp = (props) => { return <div ref={props.refProp} />; };
The above is the detailed content of How to Scroll Automatically to a Specific Element in React?. For more information, please follow other related articles on the PHP Chinese website!