Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React-Bootstrap 2022: Modal Will Not Close When X button clicked

I have been designing an web app using react and react bootstrap. In my case, I use a cdn to load the bootstrap css files and bootstrap.min.js in addition to using the react-bootstrap library.

Everything works fine, except for the close button. The close button seems to do nothing at all.

MessageBox.js:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import Modal from 'react-bootstrap/Modal'
import {useState} from 'react'

function MessageBoxComponent(title,content,showState,closeCallback){
    return (
        <Modal show={showState} onHide={closeCallback}>
            <Modal.Header closeButton>
                <Modal.Title>{title}</Modal.Title>
            </Modal.Header>
            <Modal.Body>
                {content}
            </Modal.Body>
        </Modal>
    )
}

function useMessageBox(closeCallback = ()=>{}){
    const [showState, setShowState] = useState(false)
    const [title, setTitle] = useState("")
    const [content, setContent] = useState("")
    const showMessageBox = (title,content)=>{
        setTitle(title)
        setContent(content)
        setShowState(true)
    }
    const closeMessageBox = () => {
        setShowState(false)
    }
    const component = MessageBoxComponent(title,content,showState,closeCallback)
    return [component, showMessageBox,closeMessageBox]
}

export default useMessageBox

example.js:

import useMessageBox from '../Utils/MessageBox'

function MessageBoxExample(){
    const [messageBoxComponent, showMessageBox, closeMessageBox] = useMessageBox()
    const handleClick = (evt) => {
        showMessageBox("This is the title",<span>This is the body</span>)
    }
    return <>
        <div className='container-fluid'>
            <div className='row'>
                <div className='col-sm-12'>
                    <button className='btn btn-primary' onClick={handleClick}>Open Message Box</button>
                </div>
            </div>
        </div>
        {messageBoxComponent}
        </>
}

>Solution :

You have to add a function for the onHide modal prop that will change the showState value

<Modal show={showState} onHide={() => {
   setShowState(false)
   closeCallback()
}}>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading