Scroll To A Particular Div Using Id In ReactJs Without Using Any Other Library
Scroll to a particular div using id in react without using any other library, I found a few solutions they were using scroll libraries here's the div code in my WrappedQuestionFor
Solution 1:
I use a react ref and element.scrollIntoView
to achieve this.
class App extends Component {
constructor(props) {
super(props);
this.scrollDiv = createRef();
}
render() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button
onClick={() => {
this.scrollDiv.current.scrollIntoView({ behavior: 'smooth' });
}}
>
click me!
</button>
<h2>Start editing to see some magic happen!</h2>
<div ref={this.scrollDiv}>hi</div>
</div>
);
}
}
Here's a sample codesandbox that demonstrates clicking a button and scrolling an element into view.
Solution 2:
Have you tried using Ref?
constructor(props) {
super(props);
this.myRef = React.createRef();
}
handleScrollToElement(event) {
if (<some_logic>){
window.scrollTo(0, this.myRef.current.offsetTop);
}
}
render() {
return (
<div>
<div ref={this.myRef}></div>
</div>)
}
Post a Comment for "Scroll To A Particular Div Using Id In ReactJs Without Using Any Other Library"