I am new to react and currently I am trying to set the scrollTop property of a div to a desired number. Unfortunately, it doesn't work for me. See the code below:
class Testdiv extends React.Component {
constructor(props){
super(props);
this.divRef = React.createRef();
}
componentDidMount(){
this.divRef.current.scrollTop = 100;
}
render(){
return (
<div className="testDiv" ref={this.divRef}>
Hello World<br /><br /><br /><br />
Hello World!
</div>
);
}
}
ReactDOM.render(
<Testdiv />,
document.getElementById('root')
);
And the CSS:
.testDiv{
height: 500px;
overflow: auto;
}
Here is the codeio pen for the respective code. P.S. I don't want to use Jquery. Thank you for the help.
This is a css/overflow issue, not a JS/React one. The problem is that the testDiv
is not high enough for anything to happen. Set height: 30px
on it and you'll see the difference: https://codepen.io/anon/pen/ZmBydZ
You have to make sure that the content of testDiv
is higher than the container itself and set the overflow on the y axis to scroll.
Example
class Testdiv extends React.Component {
divRef = React.createRef();
componentDidMount() {
setTimeout(() => {
this.divRef.current.scrollTop = 1000;
}, 1000);
}
render() {
return (
<div style={{ height: 200, overflowY: "scroll" }} ref={this.divRef}>
Hello World
<div style={{ height: 300 }} />
Hello World!
</div>
);
}
}
ReactDOM.render(<Testdiv />, document.getElementById("root"));
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
<div id="root"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With