Reputation: 27733
I've got a fairly sophisticated app with a main layout component, several different pages, each page having its own specialized components. I want to be able to call up a <Modal />
component from anywhere.
Currently, my solution probably isn't so hot. I have a <Modal />
in the Layout
component at the very top. So the layout is sending modal props (visible, message, buttons) down through every component so that any page or component can trigger a modal. It feels a bit wrong and messy though.
Is there another way? Maybe I can use React.cloneElement
somehow, pass it some props (including a callback to handle button click)? Or do I just have a hidden <Modal />
on every page or component that needs to invoke one?
Upvotes: 1
Views: 858
Reputation: 47172
You should invest in the Flux architecture for this one. You can then trigger an action from anywhere and have the modal pop through a property from the store.
Some pseudo code below
class Store {
constructor() {
this.registerAction('showModal', setModalVisibility);
}
setModalVisiblity(showModal) {
this.setState({showModal: showModal});
}
}
class Action {
showModal(showModal) {
return showModal;
}
}
class MyOtherComponent {
render() {
return (<div onClick={someFluxInstance.getActions().showModal}>Click</div>
}
}
class Layout {
render() {
if(this.props.showModal) {
<Modal />
}
}
}
Upvotes: 3