Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.createRef always null

Tags:

reactjs

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?

like image 487
deruse Avatar asked Aug 17 '18 01:08

deruse


Video Answer


2 Answers

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

like image 103
deruse Avatar answered Oct 24 '22 05:10

deruse


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

like image 1
Nikita Chernykh Avatar answered Oct 24 '22 05:10

Nikita Chernykh