How to make reactstrap modal open or close from parent component
You are passing the state variable isModalOpen
both as the variable indicating if it's open, and the function to use to toggle it. Use this.toggle
for toggling instead.
<ModalExample
isOpen={this.state.isModalOpen}
toggle={this.toggle}
/>
You are also using the toggleModalView
prop in the ModalExample
component, but you are passing in the function as toggle
, so you should use this.props.toggle
instead. You are also passing in isModalOpen
as isOpen
, so you should use this.props.isOpen
instead.
Hilyin
Updated on June 15, 2022Comments
-
Hilyin almost 2 years
I am trying to open / close a reactstrap modal from a parent component button, but I cannot get it to work.
I am passing the state
isModalOpen
as a prop to the childModalExample
component, and it changes as shown in the debug text fields I made, but the modal does not seem to open.Any help is appreciated. Here is a jsfiddle: https://jsfiddle.net/67wy5nqp/
const { Button, Modal, ModalHeader, ModalBody, ModalFooter } = Reactstrap; class ModalExample extends React.Component { constructor(props) { super(props); console.log(this.props); } render() { return ( <div> <br /> <label> (child) this.props.isOpen <input type="text" value={this.props.isOpen} /> </label> <Modal isOpen={this.props.isModalOpen} toggle={this.props.toggleModalView} className={this.props.className} > <ModalHeader toggle={this.props.toggleModalView}> Modal title </ModalHeader> <ModalBody> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </ModalBody> <ModalFooter> <Button color="primary" onClick={this.props.toggleModalView}> Do Something </Button> <Button color="secondary" onClick={this.props.toggleModalView}> Cancel </Button> </ModalFooter> </Modal> </div> ); } } class SampleApp extends React.Component { constructor(props) { super(props); this.state = { isModalOpen: true }; this.showModal = this.showModal.bind(this); this.toggle = this.toggle.bind(this); } toggle() { this.setState({ isModalOpen: !this.state.isModalOpen }); } showModal() { this.setState({ isModalOpen: true }); } render() { return ( <div> <ModalExample isOpen={this.state.isModalOpen} toggle={this.state.isModalOpen} /> <br /> <button className="btn btn-primary" onClick={this.toggle}> Show Modal From Parent Component </button> <br /> <label> (parent) this.state.isModalOpen: <input type="text" value={this.state.isModalOpen} /> </label> </div> ); } } ReactDOM.render(<SampleApp />, document.querySelector("#app"));