Search code examples
reactjsreact-bootstrapreact-modal

React bootstrap modal not opening when onHide function is enabled


I am noticing that my React Bootstrap modal wont open when I put the following condition : onHide={props.setShowModal(false)}. When I change it to onHide={props.setShowModal(true)} then it always stays open.

What is going wrong ?

PARENT JS --------

    const [showModal, setShowModal] = useState(false);
    <AddModal showModal={showModal} setShowModal={setShowModal} />

MODAL -------

import React, { useState, useEffect } from 'react';
import { Button, Form, FormControl, Modal } from "react-bootstrap";

const AddModal = (props) => {

    const handleClose = () => {
        props.setShowModal(false);
    }
    return (
        <Modal show={props.showModal} animation={false}
            // onHide={props.setShowModal(false)}
        >
            <Modal.Header closeButton>
                <Modal.Title>Enter Item</Modal.Title>
            </Modal.Header>
            {
        
                <Modal.Footer>
                    <Button variant="secondary" onClick={handleClose}
                    >
                        Cancel
                  </Button>
                    <Button variant="primary" onClick={handleClose}
                    >
                        Save Changes
                  </Button>
                </Modal.Footer>}
        </Modal>
    );
}

export default AddModal;

Solution

  • This happens because props.setShowModal(false) is immideatly called when your modal is rendered. You can fix it by changing your code to onHide={() => props.setShowModal(false)}.

    This is a common trap. onHide (as well as onClick and any other event handlers) expects a function that will be called when event is fired. props.setShowModal is a function, props.setShowModal(false) is not. So your options are either pass a lamda function as I suggested, or create a function

    hideModal() {
        props.setShowModal(false)
    }
    

    and pass it to onHide.