T
T
Tweedledum2019-08-27 12:09:44
React
Tweedledum, 2019-08-27 12:09:44

Why is my ref's current property null?

Hello, the problem is as follows:
there is a component A:

function А(...) {
  const anchorRef = React.createRef<HTMLDivElement>();

  return (
    <div
      className="Blabla"
      ref={anchorRef}
    >
    ...
    <B anchorRef={anchorRef} />
    ...

and there is component B where I am trying to use this anchorRef:
class B extends React.Component {
  ...
  public render() {
    ...
    console.log('-->', this.props.anchorRef);
    return (
      ...
      <Abc someprop = {this.props.anchorRef}
  ...

the element itself is visible in B, but its current property is always null, in the debugger it is also null, but if you click on it, the value appears with the mark 'Value was evaluated just now'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-08-27
@Tweedledum

At the time render is called, the elements have not yet been created or added to the DOM, so ref is null. You can get ref after mounting:

class B extends React.Component {
  componentDidMount() {
    console.log(this.props.anchorRef);
  }
}

In your case, it is more correct to use useRef, since, unlike the createRef call, it returns the same object during redraws. The createRef call, in turn, returns a new one each time.
function A {
  const anchorRef = useRef<HTMLDivElement>(null);
  // ...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question