Reputation: 380
I am using React with basic JavaScript. scrollTop seems not to be working at all. I am using the code below:
const node = ReactDOM.findDOMNode(this)
const $container = node.getElementsByClassName('comments')
$container[0].scrollTop = 10
After executing this code, scrollTop
is not working. There is already working CSS in place, with all scrolling visible for the container element.
Upvotes: 4
Views: 19954
Reputation: 13956
In your method do something like this
componentDidMount () {
window.scrollTo(0, 0);
}
render () {
return (
<div>
<p>text here</p>
<p>text here</p>
<p>text here</p>
<p>text here</p>
<button onClick={this.onScrollToTop}>Take Me To Top</button>
</div>
);
}
Upvotes: 0
Reputation: 5415
I think, you should remove findDOMNode and use ref
, when you want to get DOMElement. One of the way to solve this problem below:
const homeStyles = {
overflow: 'auto',
width: 100,
height: 100,
border: '1px solid #333'
}
class Home extends React.Component{
handleScrollTo = () => {
this.container.scrollTop = 10;
}
render(){
return (
<div ref={ el => this.container = el} style={homeStyles}>
<a onClick={this.handleScrollTo}>ScrollTo</a> <br/><br/>
content<br/>
content<br />
content<br />
content<br />
content<br />
content<br />
content<br />
content<br />
content<br />
</div>
)
}
}
Full working example: https://codesandbox.io/s/v8z7r0pxw5
Upvotes: 3