Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Scroll to the top of the page after render in react.js

I have an issue, which I have no thoughts, how to tackle. In my react component I show an extensive list of data and a few links at the base. After clicking on any of these links I fill in the list with a new collection of the links and need to scroll to the top.


The issue is - how to scroll to the top after the new collection is rendered?

'use strict';

// url of this component is #/:checklistId/:sectionId

var React = require('react'),
Router = require('react-router'),
sectionStore = require('./../stores/checklist-section-store');


function updateStateFromProps() {
var self = this;
sectionStore.getChecklistSectionContent({
checklistId: this.getParams().checklistId,
sectionId: this.getParams().sectionId
}).then(function (section) {
self.setState({
section,
componentReady: true
});
});

this.setState({componentReady: false});
}

var Checklist = React.createClass({
mixins: [Router.State],

componentWillMount: function () {
updateStateFromProps.call(this);
},

componentWillReceiveProps(){
updateStateFromProps.call(this);
},

render: function () {
if (this.state.componentReady) {
return(
<section className='checklist-section'>
<header className='section-header'>{ this.state.section.name } </header>
<Steps steps={ this.state.section.steps }/>
<a href=`#/${this.getParams().checklistId}/${this.state.section.nextSection.Id}`>
Next Section
</a>
</section>
);
} else {...}
}
});

module.exports = Checklist;
by

3 Answers

espadacoder11

componentDidMount() {
window.scrollTo(0, 0)
}

React v16.8+

useEffect(() => {
window.scrollTo(0, 0)
}, [])
sandhya6gczb
ou could use something like this. ReactDom is for react.14. Just React otherwise.

componentDidUpdate = () => { ReactDom.findDOMNode(this).scrollIntoView(); }

for React 16+

constructor(props) {
super(props)
this.childDiv = React.createRef()
}

componentDidMount = () => this.handleScroll()

componentDidUpdate = () => this.handleScroll()

handleScroll = () => {
const { index, selected } = this.props
if (index === selected) {
setTimeout(() => {
this.childDiv.current.scrollIntoView({ behavior: 'smooth' })
}, 500)
}
}
RoliMishra
Since the original solution was provided for very early version of react, here is an update:

constructor(props) {
super(props)
this.myRef = React.createRef() // Create a ref object
}

componentDidMount() {
this.myRef.current.scrollTo(0, 0);
}

render() {
return <div ref={this.myRef}></div>
} // attach the ref property to a dom element

Login / Signup to Answer the Question.