Categories
React

Add a Modal to a React App with react-modal and react-confirm-alert

Spread the love

Modals are something that we have to add often into our React app.

To make this task easier, we can use existing component libraries to add them.

In this article, we’ll look at how to add a modal into our React app with the react-modal and react-confirm-alert libraries.

Installation

We can install the library by running:

npm install --save react-modal

with NPM or:

yarn add react-modal

with Yarn.

Usage

We can use it by adding the Modal component into our React component.

To do this, we write:

import React from "react";
import Modal from "react-modal";

const customStyles = {
  content: {
    top: "50%",
    left: "50%",
    right: "auto",
    bottom: "auto",
    marginRight: "-50%",
    transform: "translate(-50%, -50%)"
  }
};

Modal.setAppElement("#root");

export default function App() {
  let subtitle;

  const [modalIsOpen, setIsOpen] = React.useState(false);
  function openModal() {
    setIsOpen(true);
  }

  function afterOpenModal() {
    subtitle.style.color = "#f00";
  }

  function closeModal() {
    setIsOpen(false);
  }

  return (
    <div>
      <button onClick={openModal}>Open Modal</button>
      <Modal
        isOpen={modalIsOpen}
        onAfterOpen={afterOpenModal}
        onRequestClose={closeModal}
        style={customStyles}
        contentLabel="Example Modal"
      >
        <h2 ref={(_subtitle) => (subtitle = _subtitle)}>Hello</h2>
        <button onClick={closeModal}>close</button>
        <div>I am a modal</div>
        <form>
          <input />
          <br />
          <button>ok</button>
          <button>cancel</button>
        </form>
      </Modal>
    </div>
  );
}

We add the customStyles object to style the items.

And we add the modalIsOpen state to control when the modal opens or closes.

The isOpen prop controls whether the modal is opened or closed.

onAfterOpen takes a function that runs code after the modal is open.

onRequestClose takes a function that runs code after the modal is closed.

style takes an object with some properties to change the styles.

contentLabel is a label for the modal.

We call Modal.setAppElement(“#root”) to make the modal component attach to the element with ID root .

react-confirm-alert

The react-confirm-alert library is another library that lets us add a modal easily into our React app.

To install it, we run:

npm install react-confirm-alert --save

We can use it by writing:

import React from "react";
import { confirmAlert } from "react-confirm-alert";
import "react-confirm-alert/src/react-confirm-alert.css";

export default function App() {
  const submit = () => {
    confirmAlert({
      title: "Confirm to submit",
      message: "Are you sure to do this.",
      buttons: [
        {
          label: "Yes",
          onClick: () => alert("Click Yes")
        },
        {
          label: "No",
          onClick: () => alert("Click No")
        }
      ]
    });
  };

  return (
    <div>
      <button onClick={submit}>Confirm dialog</button>
    </div>
  );
}

We import the confirmAlert function and call it in the submit method to open the alert dialog with it.

The title property sets the dialog title.

message sets the message content.

buttons add buttons with the given labels and the event handlers for them.

We can also make it display a custom React component as the content:

import React from "react";
import { confirmAlert } from "react-confirm-alert";
import "react-confirm-alert/src/react-confirm-alert.css";

export default function App() {
  const submit = () => {
    confirmAlert({
      customUI: ({ onClose }) => {
        return (
          <div className="custom-ui">
            <h1>Are you sure?</h1>
            <p>You want to delete this file?</p>
            <button onClick={onClose}>No</button>
            <button
              onClick={() => {
                onClose();
              }}
            >
              Yes
            </button>
          </div>
        );
      }
    });
  };

  return (
    <div>
      <button onClick={submit}>Confirm dialog</button>
    </div>
  );
}

We just return a component in the customUI method.

It gets the onClose method from the parameter and call it whenever we want to close the dialog.

Conclusion

We can add modals easily into our React app with the react-modal and react-confirm-alert libraries.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *