2

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 (
      <Form1 handler = {this.handler} />
    )
 }

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 (
      <button onClick={this.handleClick}>Continue</button>
    )
}
Noman Ali
  • 3,160
  • 10
  • 43
  • 77

1 Answers1

1

In child component you need to bind context properly:

<button onClick={this.handleClick.bind(this)}>Continue</button>

or better to bind in constructor:

this.handleClick = this.handleClick.bind(this)
// => <button onClick={this.handleClick}>Continue</button>

or call it as a method:

<button onClick={() => this.handleClick()}>Continue</button>

Finally, you need to actually call your callback:

handleClick() {
   this.props.handler();
   //     note ------^
}
dfsq
  • 191,768
  • 25
  • 236
  • 258