I've made this simple modal in React with an if condition attached to a variable. If that variable is 'true', the modal shows up. If not, then it stays hidden. I've been testing out a bit and, while it does render if the Success variable is true, and the variable does get set to false once the button is clicked, the modal doesn't get hidden when this happens (Success=false).
When the Success variable is set to false by default, the modal doesn't show up, as expected. So the issue is that the modal doesn't get hidden once the variable changes.
The code is entirely inside the App function, while the modal is inside the App function's return. The CloseSuccess function looks like this:
function CloseSuccess()
{
Success = false;
console.log(Success);
};
And the modal looks like this:
{(Success)&&
(
<div className="modal" style={{ display: 'block'}}>
<Modal.Dialog>
<Modal.Header closeButton>
<Modal.Title>Modal title</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>Modal body text goes here.</p>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={CloseSuccess}>Close</Button>
</Modal.Footer>
</Modal.Dialog>
</div>
)
}
The problem is that you are directly assigning a value to the Success variable, which does not trigger a re-render in React. In functional components, React only re-renders when state changes using the useState hook.
import { useState } from 'react';
import { Modal, Button } from 'react-bootstrap';
function App() {
const [success, setSuccess] = useState(true);
function CloseSuccess() {
setSuccess(false);
}
return (
<div>
{success && (
<div className="modal" style={{ display: 'block' }}>
<Modal.Dialog>
<Modal.Header closeButton>
<Modal.Title>Modal title</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>Modal body text goes here.</p>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={CloseSuccess}>Close</Button>
</Modal.Footer>
</Modal.Dialog>
</div>
)}
</div>
);
}