Saturday 2 June 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...