V
V
Vitaly Stolyarov2019-04-13 17:55:50
React
Vitaly Stolyarov, 2019-04-13 17:55:50

How to get ref only when element is first created by key?

As the doc says , when updating the element tree, ref will be called first with null and then with the same HTMLElement.
Assuming neither the key nor the HTMLElement has changed, I don't need ref to be called.
Is there a built-in ability to get only modified refs?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-04-13
@rockon404

It says not at all about this, but that it is not necessary to write inline functions in ref.
Not right:

class Example extends React.Component {
  ref;
  
  render() {
    return <div ref={node => this.ref = node} />;
  }
}

In this case, each update of the Example component, there will be two calls to the callback passed to ref. Once with a null argument, the second time with your element or component.
Correctly:
class Example extends React.Component {
  ref;
  createRef = node => this.ref = node;

  render() {
    return <div ref={this.createRef} />;
  }
}

In this case, when updating Example, the callback will not be called, since the reference to the callback has not changed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question