Skip to content

Passing Props to grandchild React

Child:

class Plus extends React.Component{
  constructor(props){
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick(){
    console.log('It's Working!')
    this.props.handleButtonChange()
  }

  render(){
    return (
      <div>
        <i
          className="fa fa-plus fa-2x"
          onClick={() => this.handleClick()}
        ></i>
      </div>
    );
  }
}

export default Plus;

Parent:

class NoteCreation extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div className="note-creation">
        <form action="">
          <Plus handleButtonChange={this.props.handleButtonChange} />
        </form>
      </div>
    );
  }
}

export default NoteCreation;

GrandParent Component:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      buttonStat : false
    };
    this.handleButtonChange = this.handleButtonChange(this);

  }

  handleButtonChange(){
    this.setState({
      buttonStat : true
    })
  }


  render() {

    return (
      <div className="App">
        <NoteCreation
          handleButtonChange={this.handleButtonChange}
        />
      </div>
    );
  }
}

export default App;
 

I simply want to pass the method handleButtonChange() from grandParent all the way to child (which is a button), as the button is clicked it triggers the click event which fires up this function making changes in grandparent component(i.e. setting button state) where am i wrong at or this approach is completely wrong I am really new to react. i am just want to set state in grandParent via child click event. i keep getting this error TypeError: this.props.handleButtonChange is not a function would appreciate any help

Answer

You have a typo in your top component

It should be

this.handleButtonChange = this.handleButtonChange.bind(this);

and not

this.handleButtonChange = this.handleButtonChange(this);

Alternatively you can declare your method like this

  handleButtonChange = () => {
    this.setState({
      buttonStat : true
    })
  }

without using bind at all.