To add modal functionality to any React Component follow these directions.

Example code source: /g/xampp8/htdocs/laravel/StudentTodo/StudentTodoV2

1. The Hook: Create a component: MyModal.jsx

// https://react-bootstrap.github.io/components/modal/
import React, { useState, useEffect } from 'react';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
import { useStateContext } from "../../context/ContextProvider.jsx";
import parse from 'html-react-parser'
function MyModal(props) {
  const showModal = (action) => setModalContent({ ...modalContent, show: action });
  const { modalContent, setModalContent } = useStateContext();
  if (props.show) {
    useEffect(() => {
      showModal(props.show)
    }, [])
  }
  return (
    <>
      {/* <pre>modalContent={JSON.stringify(modalContent, null, 2)}</pre> */}
      <Modal
        show={modalContent.show}
        onHide={() => showModal(false)}
        backdrop={modalContent.backdrop}
        fullscreen={modalContent.fullscreen}
        size={modalContent.size}
      >
        <Modal.Header closeButton>
          <Modal.Title>{modalContent.title}</Modal.Title>
        </Modal.Header>
        <Modal.Body>{parse(modalContent.body)}</Modal.Body>
        <Modal.Footer>
          <Button variant={modalContent.color} onClick={() => showModal(false)}>
            Close
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}
export default MyModal

 

2. Use MyModal on any component, for example: Form.jsx

import MyModal from "./MyModal";

 

  const { modalContent, setModalContent } = useStateContext();
  const [errors, setErrors] = useState([])
  const showErrorMsg = (errorsArr,set) => {
    setErrors(errorsArr);
    if(typeof set.color =="undefined") set.color = 'primary'
    if(typeof set.title =="undefined") set.title = 'Modal Message'

    console.log(`LINE 186 errorsArr=`, errorsArr);
    let HTML = `<ol className="alert alert-${set.color}">`;

    errorsArr.forEach(erroMsg => {
      HTML += `<li className="m-3">${erroMsg}</li>`;
    });

    HTML += `</ol>`;
    // UPDATE THE CONTEXT TO SHOW THE MESSAGES IN THE MODAL
    setModalContent({
      ...modalContent,
      title: set.title,
      color: set.color,
      body: HTML,
      show: true,
      backdrop: 'static'
    });

  }

 

JSX Code:

<div><MyModal show={false} /></div>

 

3. Call the modal to show a message:

showErrorMsg(["added successfuly"],{color:'success',title:"Task Edded Successfully"});

 

4. Context provider Object:

      // MODAL PROPERTIES:
  const [modalContent, setModalContent] = useState({
    title: "Default Context Modal Title",
    color: "primary", // default bootstrap color
    body: "Default Context  modal body",
    backdrop : true, // 'static' | true | false
    fullscreen: false,
    size: '', // 'sm' | 'lg' | 'xl'
    show: false
  });