Sylar Sylar - 1 month ago 10
React JSX Question

How to call parent function from child prop without an arg

I'm not looking for this method as I wont be passing in any arg.

I need to call a parent function without passing in any args.

Parent (es6):

foo(){
...
console.log("i was called");
}

<Child callFoo={this.foo} />


Child (es6):

// otherFunc() will be called by an onClick button event
otherFunc(){
...

this.props.callFoo;
}


The above does not work. This works but I do not need to do this:

Parent (es6):

foo(bool){
...
if (bool){
console.log("i was called");
}
}

<Child callFoo={this.foo} />


Child (es6):

// otherFunc() will be called by an onClick button event
otherFunc(){
...

this.props.callFoo(true);
}


Is there a way to simple call the function by
this.props.callFoo
?

Answer

You don't need to pass a boolean, but you will have to use parenthesis to execute the callFoo function. Here's your example:

class Parent extends React.Component {
  foo() {
    console.log('i was called');
  }
  render() {
    return(
      <Child callFoo={this.foo}/>
    );
  }
}

class Child extends React.Component {
  otherFunc() {
    this.props.callFoo();
  }
  render() {
    return(
      <div onClick={this.otherFunc.bind(this)}>Child</div>
    );
  }

}

React.render(<Parent/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react-with-addons.min.js"></script>
<div id="View"></div>

Comments