Close Bootstrap Modal after save


(Saša Fišter) #1

Anyone has idea how to solve this? Here is my code

import React, { Component } from 'react'
import helpers from '../../../utils/helpers'
import $ from 'jquery'

class Modal extends Component {
  constructor(props) {
    super(props)
    this.state = {
      category: '',
    }

    this.onChangeCategoryName = this.onChangeCategoryName.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }

  onChangeCategoryName(e) {
    this.setState({category: e.target.value})
  }

  handleSubmit(e) {
    e.preventDefault()
    console.log(this)
    // helpers.saveCategory(this.state).then(response => {
      
    // })
  }

  render() {
    return(
      <div className="modal fade" id="exampleModal" tabIndex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div className="modal-dialog" role="document">
          <div className="modal-content">
            <div className="modal-header">
              <h5 className="modal-title" id="exampleModalLabel">Modal title</h5>
              <button type="button" className="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <form onSubmit={this.handleSubmit}>
              <div className="modal-body">
                <input onChange={this.onChangeCategoryName} type="text" name="category" placeholder="Category name" className="mx-sm-3 form-control form-control" />
              </div>
              <div className="modal-footer">
                <button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" className="btn btn-primary">Save changes</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    )
  }
}

export default Modal

(Harihara Ravi) #2

1) Add id close button like this

<button id="hidePopUpBtn" type="button" className="close" data-dismiss="modal">&times;</button>

2) And call this function:

  closePopUp(){
      document.getElementById("hidePopUpBtn").click();
   }

(Saša Fišter) #3

Thnx, i actually did it with jQuery

$('.close').click()

basically the same thing :slight_smile:


(Shamas) #4

For anyone else coming to this topic, I strongly suggest using ‘react-bootstrap’ to avoid the tag craziness and the need to call a HTML Node.

Modal’s are described here https://react-bootstrap.github.io/components.html#modals

The solution, using that wrapping library, would be to call this.props.close(), where the close function is the same as the one passed to the Bootstrap Modal component.