Reputation: 548
I have a modal in my React one page app. I made a class component of modal and render it in some place on the page. I need to call it from many other pages in app this modal. My modal class:
class Modal extends React.Component {
constructor(props) {
super(props);
this.state = {
modalShow: false,
}
}
setModalShow(state){
this.setState({modalShow: state});
}
render(){...}
}
State of modal I keep in modal class. I want to show modal by changing state from outside Modal class. For examle something like
import Modal from './Modal'
...
Modal.setModalShow(true)
But Modal its a class, but I need to call setModalShow in instance of a class. And I don't understand how to do such a thing in React true way.
Upvotes: 0
Views: 293
Reputation: 1362
While you can, as other suggests, pass a function that will allow you to register the method to another component, this is probably not the "React" way to open a modal outside of the component (meaning that there are ways that will, I believe, be clearer to write in React than this). I would suggest either making the open state a prop or maintain the modal state in a react context (or even pass the opening function as a context, if more things happen in it than simply opening the modal), which will allow you to avoid prop drilling.
You can read about the context API in the React docs: https://reactjs.org/docs/context.html. Note that it is far simpler to use as a hook in a functional component, but it works fine with classes as well.
Upvotes: 1
Reputation: 1156
you should pass the method setModalShow
from Modal
to one of its children, and then the child component would call this.props.setModalShow(true)
.
Upvotes: 0
Reputation: 1817
That kind of behavior requires passing down that function as a child property, Like this:
class Modal extends React.Component {
constructor(props) {
super(props);
}
setModalShow(state){
this.props.showModal(true);
}
render(){
...
}
}
And wherever you use the modal, there should be the showing state like:
class ModalWrapper extends React.Component {
constructor(props) {
super(props);
this.state = {
showModal: false
}
}
showModal(state){
this.setState({modalShow: state});
}
render(){
return (<Modal showModal={showModal} />);
}
}
Upvotes: 1