a blog for those who code

Thursday 23 August 2018

How to fix Uncaught TypeError: Cannot read property 'props' of null in React.js

In this post we will be discussing about how to fix "Uncaught TypeError: Cannot read property 'props' of null" in React.js.

Lets say for example I am creating a class component called RadioGroup via extending the Component and writing a function called radioItemChanged in it which will fire whenever the RadioButton in a RadioGroup will change.

export default class RadioGroup extends Component{
  constructor(props){
    super(props);
  }

  radioItemChanged(radioButton){
    console.log('Selected Option-------' + radioButton.id);
  }
}

Now if I try to write the below code in teh render() function, it might give an error "Uncaught TypeError: Cannot read property 'props' of null".

<input type="radio" checked="checked" name="radio" 
    onChange={()=>this.radioItemChanged(radioButton)} />

This is happening because when we do not create a class using React.createClass, the `this` doesn't refrence to the Component instance so for that we have to manually bind it, so our code will change as follows :

export default class RadioGroup extends Component{
  constructor(props){
    super(props);
    this.radioItemChanged = this.radioItemChanged.bind(this);
  }

  radioItemChanged(radioButton){
    console.log('Selected Option-------' + radioButton.id);
  }	
}
Please like and share the CodingDefined.com blog if you find it useful and helpful.

No comments:

Post a Comment