'Using React.createRef in class component has current as always null

I have a simple parent and child class component:

class Parent extends.React.PureComponent {
    constructor(props, context) {
        super(props, context)
        this.childRef = React.createRef()
    }

    componentDidMount() {
        console.log(this.childRef)
    }

    render() {
        return <ChildComponent ref={this.childRef} />
    }
}

The console.log statement in the componentDidMount function prints out: { current: null }

Why is this?

My react and react-dom packages are both at 16.14.



Solution 1:[1]

In ChildComponent you need to forward ref. Example:

class ChildComponent extends Component {
  render() {
    return (
      <div ref={this.props.innerRef}>
        Div has a ref
      </div>
    )
  }
}

export default React.forwardRef((props, ref) => <ChildComponent innerRef={ref} {...props}/>);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fiodorov Andrei