Karol
Karol

Reputation: 179

React 15.4.2 Cannot read property 'ref' of null

I try get access to method of child component. It look like that: 1.Called method by ref name of component and then method

Form.js

this.ref.details.getDataFromComponent();
    <Details
        pointToShow={this.state.point}
        ref="details"
    />

Details.js

getDataFromComponent() {
  //do my stuff get state and connect to get data for component Details
}

All the time I have "Uncaught TypeError: Cannot read property 'ref' of null" React 15.4.2

Upvotes: 0

Views: 1091

Answers (2)

Fakhruddin Abdi
Fakhruddin Abdi

Reputation: 906

As Timo has mentioned to access an element using refs you should you should write this.refs...

According to the error you don't have access to this. Most probably you are calling this.ref.details.getDataFromComponent(); inside a method without access to this

For example you write :

callRef() {
  this.ref.details.getDataFromComponent();
  ....
}

If so then you don't have an access to this there. You should bind your function with this.
You can either use arrow function to auto bind with this :

callRef = () => {
  this.ref.details.getDataFromComponent();
  ....
}

Note: to use arrow function you need to use babel loader in your webpack configuration.

Or you can bind when calling the method. For example you should call callRef() method inside jsx codes like this:

< ... onClick={this.callRef.bind(this)} />

Upvotes: 0

TimoStaudinger
TimoStaudinger

Reputation: 42520

To access refs of a component, you need to use this.refs, not this.ref.

However, this does not seem to be the issue here, as the error clearly says that this is null when you are trying to access it. To determine why this is we need to see more of your code.


You should also look into defining refs using the ref callback attribute instead of the way you are doing it, as this syntax is no longer recommended and may be removed in future releases.

Upvotes: 1

Related Questions