Search code examples
javascriptreactjsbootstrap-modalreact-bootstrap

how to show bootstrap Modal in another component react js


I am using react bootstrap Modal now I have Modal I want to show that modal in different components for the provided edit functionality. how I can archive this

UpdateUserModal.js

import React,{useState} from 'react'
import {Modal} from 'react-bootstrap'

const UpdateUserModal = () => {

    const [show, setShow] = useState(false);

    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);

  return (
    <div>
        <Button variant="primary" onClick={handleShow}>
        Launch demo modal
      </Button>

      <Modal show={show} onHide={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={handleClose}>
            Close
          </Button>
          <Button variant="primary" onClick={handleClose}>
            Save Changes
          </Button>
        </Modal.Footer>
      </Modal>
    </div>
  )
}

export default UpdateUserModal

I want to add my <button type="submit" className="btn btn-warning mx-1">{<FaUserEdit/>} Edite</button> on different component button

Update: enter image description here


Solution

  • Update your UpdateUserModal.js with this.

    import {Modal} from 'react-bootstrap'
    
    const UpdateUserModal = (props) => {
    const {show, handleClose, handleShow} = props
    
    
      return (
        <div>
            <Button variant="primary" onClick={handleShow}>
            Launch demo modal
          </Button>
    
          <Modal show={show} onHide={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={handleClose}>
                Close
              </Button>
              <Button variant="primary" onClick={handleClose}>
                Save Changes
              </Button>
            </Modal.Footer>
          </Modal>
        </div>
      )
    }
    
    export default UpdateUserModal
    

    Now, wherever you wish to use this modal, create this state and function there:

    const [show, setShow] = useState(false);
    
    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);
    

    Now on your edit button where you want this, update you state from button click,

    onClick={()=> handleShow()}
    

    and then import and call:

    import UpdateUserModal from "./UpdateUserModal";
    <UpdateUserModal show={show} handleClose={handleClose} handleShow={handleShow}/>