I am trying to open a modal from another component. this is in my parent component:
import { Button, Modal } from 'react-bootstrap';
import React, { useState } from 'react';
import './App.css';
import ModalB from './ModalB';
function App() {
const [showA, setShowA] = useState(false);
const [showB, setShowB] = useState(false);
const handleCloseA = () => setShowA(false);
const handleShowA = () => setShowA(true);
const handleShowB = ({ handleShow }) => {
setShowB(handleShow);
};
return (
<div className="App">
<header className="App-header">
<Button variant="primary" onClick={handleShowA}>Open A</Button>
<Button variant="primary" onClick={handleShowB}>Open B</Button>
<Modal show={showA} onHide={handleCloseA}>
<Modal.Header closeButton>
<Modal.Title>In Modal A</Modal.Title>
</Modal.Header>
</Modal>
<ModalB isModalVisible={showB}></ModalB>
</header>
</div>
);
}
export default App;
And Modal B component:
import { Button, Modal } from 'react-bootstrap';
import React, { useState } from 'react';
import { propTypes } from 'react-bootstrap/esm/Image';
const ModalB = (props) => {
const [showB, setShowB] = useState(false);
const handleCloseB = () => setShowB(false);
const handleShowB = () => setShowB(true);
return (
<div>
<Modal show={props.isModalVisible} onHide={handleCloseB}>
<Modal.Header closeButton>
<Modal.Title>In Modal B</Modal.Title>
</Modal.Header>
</Modal>
</div>
);
}
export default ModalB;
The problem is to display B from the main component. While displaying modalA is simple, I don't understand how to tell B to display from the main component.
Thanks for your help.
Remove the "show" state from ModalB and pass in the handleShowB handler from the parent.
const ModalB = ({ isModalVisible, handleShowB }) => {
return (
<div>
<Modal show={props.isModalVisible} onHide={handleShowB}>
<Modal.Header closeButton>
<Modal.Title>In Modal B</Modal.Title>
</Modal.Header>
</Modal>
</div>
);
}
In parent pass handleShowB handler. Here we just pass an anonymous callback to call the setShowB state updater and update the showB state to be false.
<ModalB
isModalVisible={showB}
handleShowB={() => setShowB(false)}
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With