Reputation: 2205
I have a <Modal/>
component in my APP.
Modal has two methods show()
and hide()
where I change the state of the component.
In my App I have:
<App>
<Modal ref="modal"/>
<Menu openModal={this.refs.modal.show}/>
</App>
But inside the Menu this.props.openModal
is undefined.
Can someone explain me why?
Upvotes: 1
Views: 555
Reputation: 1159
It's probably because at the time of rendering, this.refs.modal hasn't been defined yet.
What you should do is have some state on the App component, then a callback to change that state, which gets passed down to the Modal as a prop.
getInitialState: function() {
return {modalOpen: false};
},
setModalOpen: function(open) {
this.setState({modalOpen: false});
}
...
render: function () {
return (
<App>
<Modal open={this.state.modalOpen} setOpen={this.setModalOpen}/>
<Menu openModal={this.setModalOpen}/>
</App>
);
}
You can then read the state of the modal as a prop, but note also that the Modal component should use the callback to set the state on the App component and only use the prop, not override it with it's own internal state.
Upvotes: 4