iDontKnowBetter iDontKnowBetter - 6 months ago 9
Javascript Question

When nesting components this.props.parent returns "undefined". How do I access a parents function?

For example, I have:

<Page><Content1 /><Page>
<Page><Content2 /><Page>


Where Slide is:

var Page = React.createClass({
getInitialState: function() {
return {shouldHide: true};
},

hide: function() {
this.state.shouldHide = true;
},

show: function() {
this.state.shouldHide = false;
},

render: function() {
return (
<div className={this.state.shouldHide ? 'hidden' : ''}>
{this.props.children}
</div>
);
}
});


I want to be able to call the
.hide()
and
.show()
functions from the child component. Is this possible?

QoP QoP
Answer

You can use React.cloneElement to add props to your children in order to use your parent methods

render: function() {
        let children = React.cloneElement(this.props.children || <div/>,
                            {show: this.show, hide: this.hide });
        return (
          <div className={this.state.shouldHide ? 'hidden' : ''}>
             {children}
          </div>
);

And you shouldn't mutate your state directly, use this.setState instead.

this

hide: function() {
  this.state.shouldHide = true;
},

show: function() {
  this.state.shouldHide = false;
},

should be

hide: function() {
  this.setState({shouldHide: true});
},

show: function() {
  this.setState({shouldHide: false});
},