deruse
deruse

Reputation: 2881

React.createRef always null

I am probably doing something really stupid here, but for the life of me, I cannot figure out why ref is always null.

import React, { PureComponent } from 'react';

class MyComponent extends PureComponent {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
    console.log(this.myRef);
  }

  componentDidMount() {
    console.log(this.myRef);
  }

  componentWillUnmount() {
    console.log('unmounting');
  }

  render() {
    console.log(this.myRef);
    return (
      <div ref={this.myRef}>
        foobar
      </div>
    );
  }
}

Console:

{current: null}
{current: null}
{current: null}

I am on React 16.3. What am I missing?

Upvotes: 9

Views: 8643

Answers (3)

Eduardo Portet
Eduardo Portet

Reputation: 287

It could also be due to your element not mounting at componentDidMount()

Instead try printing the value inside of a componentDidUpdate()

Upvotes: 0

Nikita Chernykh
Nikita Chernykh

Reputation: 270

I used this.myRef.value that retured me null. Now I use this.myRef.current that works!

Upvotes: 1

deruse
deruse

Reputation: 2881

omg, I was on react 16.3 but react-dom 16.2. bumping react-dom to 16.3 fixed the issue.

Upvotes: 12

Related Questions