CodexBloom - Programming Q&A Platform

Bootstrap 5 Modal Not Closing on Overlay Click in React App

👀 Views: 104 💬 Answers: 1 📅 Created: 2025-06-27
react bootstrap modal JavaScript

I'm following best practices but I'm having trouble with Bootstrap 5 modals in my React application. I have a modal that I want to close when the user clicks outside of it (on the overlay), but it's not functioning as expected. I’m using React 17 and Bootstrap 5.1.3, and I initialized the modal using the built-in Bootstrap JavaScript. Here's the relevant code snippet for my modal: ```jsx import React from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import { Modal, Button } from 'react-bootstrap'; function MyModal({ show, handleClose }) { return ( <Modal show={show} onHide={handleClose} backdrop="static"> <Modal.Header closeButton> <Modal.Title>My Modal</Modal.Title> </Modal.Header> <Modal.Body> This is a Bootstrap modal example. </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={handleClose}>Close</Button> </Modal.Footer> </Modal> ); } ``` When I set the `backdrop` prop to `"static"`, it stops the modal from closing when the overlay is clicked, which is not what I want. But if I remove it completely, the modal closes on overlay clicks, even when it's not supposed to. I’m trying to achieve a behavior where it closes on overlay clicks but still allows for the close button to independently close the modal. The modal opens correctly, and the close button works, but I need to get the backdrop click behavior right. I’ve also tried adding an event listener on the modal but faced issues with dismounting in React. Here's what I attempted: ```jsx React.useEffect(() => { const handleBackdropClick = (event) => { if (event.target.classList.contains('modal')) { handleClose(); } }; document.querySelector('.modal').addEventListener('click', handleBackdropClick); return () => { document.querySelector('.modal').removeEventListener('click', handleBackdropClick); }; }, []); ``` However, I get an behavior "want to read properties of null (reading 'addEventListener')" because the modal element doesn't exist in the DOM during the initial render. Is there a proper way to manage closing the modal by clicking the overlay in React using Bootstrap without running into these issues? Any insights would be greatly appreciated! Hoping someone can shed some light on this.