ScrollIntoView using React refs

We are trying to jump to a specific component when the user closes another component.

Our example is very similar to the one 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 present a large list of cards and want 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, so we cannot connect to a specific element, and then start it when the user returns to view this component.

I would like to help you decide how to solve this problem.

+7
javascript dom reactjs react-dom ref
source share
2 answers

Where are you trying to call this.refs[elem].scrollIntoView() ? You should work with ref inside componentDidMount or componentDidUpdate , and not inside the render method.

+1
source share

I solved my specific problem 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); } }} 
0
source share

All Articles