13

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.

3
  • My real example, I am not using functional components at any level. Commented Dec 13, 2017 at 18:08
  • 1
    when you assign ref using callback function, you no longer access it using this.refs, rather the class variable name, like this.inputElement Commented Dec 13, 2017 at 18:15
  • @ShubhamKhatri thanks for that, turns out our brains were dead, we looked at your comment and that really helped us. Commented Dec 14, 2017 at 16:12

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, we were already trying to do that without any luck, managed to fix it though! :)
1

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);
  } 
}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.