Jessie Richardson Jessie Richardson - 3 months ago 22
React JSX Question

Passing Event Handler From Grandparent to GrandChild Component in Reactjs

I understand how to pass a click event from a parent component to a child component in React, but don't understand how I can pass it from a grandparent to a grandchild without making the parent clickable.

In the following example, I'd like for the parent div to close upon clicking the grandchild div.

Here is my code, which does not work. Thx!

var Grandparent = React.createClass({
getInitialState: function() {
return {open: true};
},
close: function() {
this.setState({open: false});
},
render() {
var grandparentBox={backgroundColor: 'yellow', height: 400, width: 400};
return <div style = {grandparentBox}><Parent open={this.state.open} close = {this.close}/></div>;
}
});

var Parent = React.createClass({
render() {
var parentBox={backgroundColor: 'red', height: 100, width: 100};
if (this.props.open == true) {
return <div close={this.props.close} style = {parentBox}><Grandchild/></div>
}
else {
return null;
}
}
});

var Grandchild = React.createClass({
render() {
var grandchildBox={backgroundColor: 'black', height: 20, width: 20, top: 0};
return <div onClick={this.props.close} style = {grandchildBox}></div>

}
});

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

Answer

It looks like you need to pass the close method as a prop to the Grandchild component (instead of the div that's wrapping it). As it is, Grandchild doesn't have a method this.props.close...

var Parent = React.createClass({
    render() {
        var parentBoxStyle = {backgroundColor: 'red', height: 100, width: 100};
        if (this.props.open == true) {
            return <div style={parentBoxStyle}>
                <Grandchild close={this.props.close} />
            </div>
        }
        else {
            return null;
        }
    }
});
Comments