Saturday, June 2, 2018

javascript - Cannot read property 'props' of null - Reactjs




Basically i want to call a function from parent component in child component. That function will change parent component's state.



I have created a handler in parent and passed it as prop to child component.
Now i want to call it in child component.



Parent:



  state = { formstep: '1'}
constructor(props) {

super(props)
this.handler = this.handler.bind(this)
}
handler(e) {
e.preventDefault()
this.setState({
formstep: '2'
})
}


render () {
return (

)
}


And in child when I try to call handler function it says





Cannot read property 'props' of null




Child:



handleClick() {
//Saving Some data from form
//and calling parent function
this.props.handler;
}


render () {
return (

)
}

Answer



In child component you need to bind context properly:







or better to bind in constructor:



this.handleClick = this.handleClick.bind(this)
// =>


or call it as a method:







Finally, you need to actually call your callback:



handleClick() {
this.props.handler();
// note ------^
}


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...