Search code examples
reactjsbootstrap-modal

I'm not understanding who the closeButton proprieties works in React Bootstrap modal


I'm trying to add a modal to my webapp using React Bootstrap Modal and I'm strugling to understand the proprieties closeButton of the <Modal.Header>, here's how i've setup my modal

<Modal show={this.state.show}>
    <Modal.Header closeButton>
        <Modal.Title>Aggiungi un conto corrente</Modal.Title>
    </Modal.Header>
    <Modal.Body></Modal.Body>
    <Modal.Footer>
        <Button variant="secondary">
            Annulla
        </Button>
        <Button varian="primary">
            Salva
        </Button>
    </Modal.Footer>
</Modal>

the show state is setted to false in the constructor

this.state = {
    show: false
}

this is all part of a class and I show the modal using this method

    showModalAdd(){
        this.setState({
            show: true
        })
    }

I'm really strugling to understand what to do, I would really appricieate if you would be so kind to point me in the right direction.

I've tryied to implement a methodd handleClose as in the doc but that was in a function situation, I'm implementing it with a class


Solution

  • closeButton is a boolean value that Specifies whether the ModalHeader Component should contain a close button or not . When clicking this button, it will fire an onHide function in the modal component .

    <Modal.Header closeButton> =====> will add a close button to the model header

    <Modal show={this.state.show} onHide={this.handleClose}> =====> clicking the above button will fire onHide function

    this a demo how it works using your code :

    import React from "react";
    import Button from "react-bootstrap/Button";
    import Modal from "react-bootstrap/Modal";
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          show: false,
        };
        this.handleShow = this.handleShow.bind(this);
        this.handleClose = this.handleClose.bind(this);
      }
      handleShow() {
        this.setState({ show: !this.state.show });
      }
      handleClose() {
        this.setState({ show: !this.state.show });
      }
    
      render() {
        return (
          <div>
            <Modal show={this.state.show} onHide={this.handleClose}>
              <Modal.Header closeButton>
                <Modal.Title>Aggiungi un conto corrente</Modal.Title>
              </Modal.Header>
              <Modal.Body> kjkjqskjqjkkjqkjksqkj</Modal.Body>
              <Modal.Footer>
                <Button variant="secondary">Annulla</Button>
                <Button varian="primary">Salva</Button>
              </Modal.Footer>
            </Modal>
            <button type="text" onClick={this.handleShow}>
              {" "}
              open modal
            </button>
          </div>
        );
      }
    }
    
    export default App;