scrollIntoView using React refs
Solution 1
Where are you trying to call this.refs[elem].scrollIntoView()
? You should be working with ref
s inside componentDidMount
or componentDidUpdate
, not inside the render
method.
Solution 2
I've solved my specific issue by providing an if statement written below in my Grandparent component.
inputRef={el => {
if (el && el.id == this.state.selectedBuildingRef) {
this.myelement.scrollIntoView();
window.scrollBy(0, -65);
}
}}
Sohil Pandya
Updated on June 04, 2022Comments
-
Sohil Pandya almost 2 years
We are trying to scroll to a specific component when the user closes another component.
Our example is very similar to that down below, taken from https://reactjs.org/docs/refs-and-the-dom.html#exposing-dom-refs-to-parent-components
function CustomComponents(props) { const items = [1,2,3,4].map((x, i) => return ( <div ref={props.inputRef} key={i}> x + hello </div> ) return ( <div> { items } </div> ); } function Parent(props) { return ( <div> <CustomComponents inputRef={props.inputRef} /> </div> ); } class Grandparent extends React.Component { render() { return ( <Parent inputRef={el => this.inputElement = el} /> ); } }
We are rendering a big list of cards and want to be able to scroll to a specific card by calling
this.refs[elem].scrollIntoView()
But our problem is that calling
this.refs
returns an empty object at all levels, and so we are unable to attach to a specific element and then fire it when the user arrives back to view this component.Would like some help on how one would go about solving this issue.
-
Sohil Pandya over 6 yearsYeah, we were already trying to do that without any luck, managed to fix it though! :)