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();
}
ponentDidMount(){
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.
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();
}
ponentDidMount(){
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.
Share Improve this question asked Nov 12, 2018 at 15:05 anwesh mohapatraanwesh mohapatra 1,0934 gold badges12 silver badges22 bronze badges2 Answers
Reset to default 3This 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();
ponentDidMount() {
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./[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg./[email protected]/umd/react-dom.production.min.js"></script>
<div id="root"></div>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744251695a4565199.html
评论列表(0条)