I have the following problem: I have moved the markup/code of a modal to a separate component in react because the file was getting rather long and I might want to use it somewhere else.
I got it so that I can open it and close it, however if I want to reopen it it does not work. I suspect it is because I set a flag to show it to false
when I click close, but I cannot reset it so it reopens.
My code is as follows
In the main component
const [showModal, setShowModal] = React.useState(false);
...
<button
onClick={() => setShowModal(true)}
type="button"
claseName="infobutton"
>
<i class="fas fa-info-circle"></i>
</button>
...
<InfoModal show={showModal} />
In the InfoModal component
const [ShowModal, setShowModal] = useState(true);
return (
<>
{show && ShowModal ? (
...
<button
className="closeButton"
onClick={() => setShowModal(false)}
>
<span className="closeButton">
×
</span>
</button>
...
</>
);
What have I done wrong here and should there be a better way of doing this. Any suggestions are greatly appreciated
You could remove the duplicate state from InfoModal, and instead pass your setShowModal
from the Main component as a prop to InfoModal, eg <InfoModal show={showModal} onClose={() => setShowModal(false)} />
// Main Component
const [showModal, setShowModal] = React.useState(false);
...
<button
onClick={() => setShowModal(true)}
type="button"
claseName="infobutton"
>
<i class="fas fa-info-circle"></i>
</button>
...
<InfoModal show={showModal} onClose={() => setShowModal(false)} />
// InfoModal Component
return (
<>
{show ? (
...
<button
className="closeButton"
onClick={onClose}
>
<span className="closeButton">
×
</span>
</button>
...
)}
</>
);
Modify your second component in this way it should work. In your component you never set your state to true again and it never opens the modal
const [ShowModal, setShowModal] = useState(true);
useEffect(() => {
setShowModal(show)
}, [props]);
return (
<>
{show ? (
...
<button
className="closeButton"
onClick={() => setShowModal(false)}
>
<span className="closeButton">
×
</span>
</button>
...
</>
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.