Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing a react bootstrap modal with escape key

I have 6 buttons which, when clicked, activate a modal. This is written in React.

//Since I have 6 different modals, giving each of them an id would distinguish them
onCloseModal(id) {
    this.setState({
        open: false,
        modalShown: id
    })
}

render() {
    return (
        <Modal onHide={this.onCloseModal.bind(this, item.id)} keyboard={true}>
            <Modal.Header closeButton={true} onHide={this.onCloseModal.bind(this)}>
            </Modal.Header>
        </Modal>
    )
}

I have keyboard={true}, which according to the documentation at https://react-bootstrap.github.io/components.html#modals-props, pressing the Escape key would exit the modal. It isn't working however. I believe that I have everything set up because each of my buttons has a unique ID - why isn't the escape key responding?

Here's an image of the modal in action.

enter image description here

like image 920
patrickhuang94 Avatar asked Oct 10 '16 04:10

patrickhuang94


People also ask

How do I turn off modal on Escape key?

This modal can be closed with the escape key on your keyboard. Note: You need to press the tab key on the keyboard to first enter the modal window, and then press the Esc key.

How do you close a modal in react?

Now, when a user clicks the Tab marked Show the Modal! , they'll open up the Modal, and when they click the x or close buttons on the component the Modal will close. Easy-peasy. React-Bootstrap is one of many custom frameworks freely available to power-up our frontend development needs.

Should escape close a modal?

When keyboard users tabs into modals (like a popup or dialog), focus should remain in that window. This helps prevent users from accidentally moving focus outside the modal without closing it. Users should be able to use the ESC key to close the modal.

How do I close a Bootstrap modal?

Clicking on the modal “backdrop” will automatically close the modal. Bootstrap only supports one modal window at a time.


1 Answers

It appears that your component state isn't properly representing the state of the modals. I wrote you an example (which might not be best practice?) that shows how you can handle the state in a more specified way.

onCloseModal() {
  this.setState({
    modalShown: 0
  })
}

onShowModal(id) {
  this.setState({
    modalShown: id
  })
}

checkModal(id) {
  if (id == this.state.modalShown) {
    return true;
  } else {
    return false;
  }
}

<Modal show={this.checkModal(item.id)} onHide={this.onCloseModal.bind(this)}</Modal>
like image 165
Fabian Schultz Avatar answered Sep 20 '22 19:09

Fabian Schultz