scrollIntoView using React refs

Sohil Pandya picture Sohil Pandya · Dec 13, 2017 · Viewed 12.1k times · Source

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.

Answer

claireinez picture claireinez · Dec 14, 2017

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