Search code examples
reactjsreact-bootstrap

How to call an individual modal box component in react?


I wanted to open/load a react bootstrap model box component (Modalbox.js) to App.js, but the modal box open button code in App.js, how to do that? please help. In App.js, there will be multiple buttons for call multiple type modalboxs. modalbox.js should contain only modal box code. modal launch buttons should be in App.js

<button variant="primary" onClick={handleShow}>Launch demo modal</button>

https://codesandbox.io/s/individual-modal-box-component-ti6ugg


Solution

  • I have added only functionality on the show and hide here is code so that you may get the idea props and manage the state accordingly all remaining code it feels free to add more functionality and custome state

        import "./styles.css";
        import Modalbox from "./Modalbox";
        import { useState } from "react";
        export default function App() {
        const[handleShow,sethandleShow] = useState(false)
      return (
    <div className="App">
      <button variant="primary" onClick={()=>sethandleShow(!handleShow)}>
        Launch demo modal
      </button>
     <Modalbox handleShow={handleShow} sethandleShow={sethandleShow} />
    </div>
     );
    }
    

    modalbox.js

       import React, { useState } from "react";
      import { Modal, Button } from "react-bootstrap";
    
      function Modalbox(props) {
      const [modalshow, setShow] = useState(false);
      const handleClose = () => setShow(false);
      const handleShow = () => setShow(true);
    
       return (
    <div>
      {/* <Modal show={modalshow} onHide={handleClose}> */}
      <Modal show={props.handleShow} onHide={()=>props.sethandleShow(!props.handleShow)}>
        <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={()=>props.sethandleShow(!props.handleShow)}>
            Close
          </Button>
          <Button variant="primary" onClick={handleClose}>
            Save Changes
          </Button>
        </Modal.Footer>
      </Modal>
    </div>
      );
     }
    
     export default Modalbox;