I am trying to put a modal dialog using react-bootstrap and having issues.
I have a "HintComponent" which consists of a bunch of buttons
<div className="col-5 d-grid gap-2 borderGeneral">
<button className="buttonGeneral" >Label here</button>
<button className="buttonGeneral">SUMMARY</button>
</div>
and I want to launch a Modal dialog on clicking a button.
Looking at the react-bootstrap site, I have the following (taken straight from the site)
import React, {useState} from 'react';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
import render from 'react-dom';
function Example() {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
return (
<>
<Button variant="primary" onClick={handleShow}>
Launch demo modal
</Button>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Modal heading</Modal.Title>
</Modal.Header>
<Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Close
</Button>
<Button variant="primary" onClick={handleClose}>
Save Changes
</Button>
</Modal.Footer>
</Modal>
</>
);
}
render(<Example />);
My issue is - how do I call the Modal from the HintComponent? If I try to import the Modal (in this case ) and call it as just I get a warning about module having no exports.
Can anyone give me a hint?
CodePudding user response:
Hi very simple you need to use this component in your HintComponent
and pass a prop showModal={true}
but before this, you need to receive that prop in your modal component and set it in state using React.useEffect
So your final code will be like below:
ModalComponent
import React, {useState} from 'react';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
import render from 'react-dom';
function Example(props) {
const {showModal = false, onClose = ()=>{}} = props;
const [show, setShow] = useState(showModal);
React.useEffect(()=>{
setShow(showModal);
},[showModal]);
const handleClose = () => {
setShow(false);
// just to have custom function for modal close which will be used can be used in HintComponent maybe you want to perform somehting else after modal close.
typeof onClose === 'function' && onClose();
};
const handleShow = () => setShow(true);
return (
<>
<Button variant="primary" onClick={handleShow}>
Launch demo modal
</Button>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Modal heading</Modal.Title>
</Modal.Header>
<Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Close
</Button>
<Button variant="primary" onClick={handleClose}>
Save Changes
</Button>
</Modal.Footer>
</Modal>
</>
);
}
render(<Example />);
I would recommend do not manage Modal visibility in its component but control it from the parent component in your case HintComponent.