S
S
Sergey2020-12-15 09:09:53
JavaScript
Sergey, 2020-12-15 09:09:53

How to pass a ref to another component?

Hello.

There are two different components. You need to implement something like this:

class App extends React.Component {
  bottomRef = React.createRef();

  onClick = () => {
    this.bottomRef.current.scrollIntoView();
  };

  render() {
    return (
      <div>
        <button onClick={this.onClick}>Scroll to bottom</button>
        <div style={{ height: 2000 }} />
        <div ref={this.bottomRef}>bottom</div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));


Only a ref link and a button on which the handler is hung in different components and so props cannot be thrown. What other options might there be?

PS How stupid is it to use getElementById in a React component and what are the pitfalls in terms of optimizing this approach?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Shcherbakov, 2020-12-15
@Simply1993

You need to use either forwardRef, or pass ref through props (only use the prop name not ref, but for example innerRef) The
first option will be preferable and more correct.
https://ru.reactjs.org/docs/forwarding-refs.html#f...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question