React-modal: Modal.Header closeButton Does Not Work

Created on 8 Jun 2021  路  3Comments  路  Source: reactjs/react-modal

Summary:

Hi, I am pretty new to react, and working on React Modal component. Followed the example on react doc. Can display the Modal, but found it impossible to close the modal.
The CloseButton cannot close the modal. For the code example, all close actions failed (CloseButton within the header, Close and Save Changes button).

Steps to reproduce:

Here is the code

import React, {Component, useState} from "react";
import PropTypes from "prop-types";
import { Container, Row, Col, Button, Modal } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";

export default class Details extends Component {
    constructor(props) {
        super(props);

        this.state = {
            showModal: true
        };

        this.handleOpen = this.handleOpen.bind(this);
        this.handleClose = this.handleClose.bind(this);
    }

    handleClose() {
        this.state.showModal = false
    }

    handleOpen() {
        this.setState({
            showModal: true
        });
    }

    render() {
        return (
                <Modal show={this.state.showModal} onHide={this.handleClose}>
                <Modal.Header closeButton>
                    <Modal.Title>Modal heading</Modal.Title>
                </Modal.Header>
                <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
                <Modal.Footer>
                    <Button variant="secondary" onClick={this.handleClose}>
                    Close
                    </Button>
                    <Button variant="primary" onClick={this.handleClose}>
                    Save Changes
                    </Button>
                </Modal.Footer>
                </Modal>
        );
    }
}

Expected behavior:

The modal should be closed by clicking the closebutton.

Additional notes:

The react version is 16.14.0.
I tried to add the following around <Modal></Modal>, but it doesn't work.

<div onClick={e => e.stopPropagation()}>
</div>

Also tried to add e.stopPropagation(); to handleClose, failed again.

Most helpful comment

If you need further assistance ask on react-bootstraps github. This is not related to react-modal.

All 3 comments

Change:

handleClose() {
  this.state.showModal = false
}

to:

handleClose() {
  this.setState({ showModal: false });
}

If you need further assistance ask on react-bootstraps github. This is not related to react-modal.

@yaoyao1024 did that fixed your problem?

Was this page helpful?
0 / 5 - 0 ratings