Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a parent component's method onClick in React

So as the title suggests I'm just trying to access a parent component's method in React via a child component. I understand this can be accomplished via props, however I'm attempting to do it via an onClick event and it doesn't seem to like that. Here is a basic example of my problem.

var Child = React.createClass({

render: function() {
    return (

        <button onClick={this.onClick}>Click Here</button>
  );
 }
});   


var Parent = React.createClass({

onClick: function() {
    console.log('I've been clicked');
  },


render: function() {
    return (

        <Child />

  );
 }
});

ReactDOM.render(<Parent />, document.getElementById('Parent'));

How do I get the Child component's button onClick event to fire the Parent component's onClick method? Appreciate the help.

like image 557
jdev99 Avatar asked Dec 09 '25 19:12

jdev99


1 Answers

You can pass Parent's onClick function to Child as a prop:

<Child myClick={this.onClick} />

and then use it in Child:

<button onClick={this.props.myClick}>Click Here</button>

Entire code:

var Child = React.createClass({
    render: function() {
        return (<button onClick={this.props.myClick}>Click Here</button>)
    }
});

var Parent = React.createClass({
    onClick: function() {
        console.log("I've been clicked");
    },

    render: function() {
        return (<Child myClick={this.onClick} />);
    }
});

ReactDOM.render(<Parent />, document.getElementById('container'));
like image 192
qkr Avatar answered Dec 12 '25 08:12

qkr