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

Advertisements

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:

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()
}}>

Leave a ReplyCancel reply