[React] How do I call a parent method within child component method

Below is what I’m currently trying, while this.props.handleClick works for onClick attribute in the child component, it doesn’t work when called within the child component method.

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
}
  handleClick(e) {
    console.log('It works!');
}
  render() {
    return (<div><ChildComponent handleClick={this.handleClick} /></div>)
}
}

class ChildComponent extends React.Component {
  someFunc() {
    this.props.handleClick
}  
  render() {
    return (<button onClick={this.props.handleClick}></button>)
}}

link to the full codes on codepen: https://codepen.io/prieton/pen/ZExWbyY?editors=1111

handleClick is a function, right? You call a function by using parens.

The reason you don’t need the parens here:

onClick={this.props.handleClick}

Is because you are passing the click handler a function, you are not actually calling the function here.

1 Like

That makes sense. Thanks!