Automatically going to a div element created in React Virtual Dom
Automatically going to a div element created in React Virtual Dom
My webpage uses React components. At the render function of one of its components div elements that looks like:
<div id='myid'>
{/* ... */}
</div>
are being used. After reloading a page we need to go to one of those divs. For example, after reloading that page we could automatically need to go to the <div> element with id equals to myid. Notice that that <div> is in React virtual DOM so functions like document.getElementById might not work (as it is happening with me). Is this possible?
<div>
myid
<div>
document.getElementById
3 Answers
3
The <div> and the id will end up in the document when the component is mounted, so you could scroll there in the componentDidMount hook.
<div>
id
componentDidMount
Example (CodeSandbox)
class App extends React.Component {
componentDidMount() {
document.getElementById("myid").scrollIntoView();
}
render() {
return (
<div>
<div style={{ height: 1000 }}>Hello CodeSandbox</div>
<div style={{ height: 1000 }} id="myid">
Scroll here
</div>
</div>
);
}
}
@JoseCabreraZuniga I understand. I updated the answer. It's just an example, but you could handle the logic for picking the
id however you like.– Tholle
Jun 30 at 14:53
id
You should use a react
ref instead of searching the dom for the element. DOM querying is almost never neccesary when working with react.– trixn
Jun 30 at 14:58
ref
I am starting to to consider a call back following this example. Thx
– Jose Cabrera Zuniga
Jun 30 at 15:00
@trixn Yes, my original answer used
ref, but that does not fit Jose's use case.– Tholle
Jun 30 at 15:01
ref
You can still get the element using findDOMNode
const div = ReactDOM.findDOMNode(this.refs.mydiv);
const div = ReactDOM.findDOMNode(this.refs.mydiv);
Then in the render function
<div ref="mydiv"></div>
<div ref="mydiv"></div>
And at last
window.scrollTo(0, div.offsetTop);
window.scrollTo(0, div.offsetTop);
If the element is rendered by react you should use a ref to get the element to call scrollIntoView() on it:
ref
scrollIntoView()
class MyComponent extends Component {
ref = elem => elem.scrollIntoView();
render() {
return (
<div ref={this.ref}>{/* ... */}</div>
);
}
}
Using getElementById() or React.findDOMNode may also work but there you have the problem that you need to know if the component already mounted. If you do the scrolling inside the component (which is recommended) using a ref is the best solution.
getElementById()
React.findDOMNode
ref
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
the problem is that we have several divs like the mentioned above with id='myid' within the same virtual dom page and we will like to, after reloading, sometimes go to one of them and sometimes to go to other.
– Jose Cabrera Zuniga
Jun 30 at 14:52