0

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;
test dummy
  • 81
  • 4
  • 11

1 Answers1

2

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.

user3272018
  • 2,309
  • 5
  • 26
  • 48
  • Thank you. For others who will read this in the future. Can you provide a 1 line explanation as to why it happens ? – test dummy Aug 16 '20 at 04:36
  • Just added a note why that is happening. Also you're not the first one to fall for it, see [this question](https://stackoverflow.com/questions/45246933/onclick-not-firing-in-react) or [this](https://stackoverflow.com/questions/34226076/why-is-my-onclick-being-called-on-render-react-js). – user3272018 Aug 16 '20 at 04:44
  • Great. Thank you! – test dummy Aug 16 '20 at 18:03