15 Août Se positionner à un div onload page – React (scrollIntoView)
Solution 1:
On met dans notre constructor
constructor(props) {
super(props);
this.myRef = React.createRef();
}
Deuxièmement on ajoute une méthode componentDidUpdate()
componentDidUpdate() {
const node = this.myRef.current;
if (node) {
node.scrollIntoView();
}
}
Et finalement dans la partie render on ajoute une div avec un attribut myRef
<div className={styles.autoscroll} ref={this.myRef}></div>
Solution 2:
La première étape est d’importer ReactDOM sur notre component
import ReactDOM from 'react-dom';
La deuxième étape est l’ajout de la méthode componentDidUpdate dans notre Class
/* CLASS */
...
componentDidUpdate() {
const hash = 'node';
if (hash) {
const node = ReactDOM.findDOMNode(this.refs[hash]);
if (node) {
node.scrollIntoView();
}
}
}
Et finalement dans la partie render on ajoute une div avec un attribut ref
<div ref="node"></div>