Practical React series: 3. React Modal

Sabiya TabassumSabiya Tabassum
1 min read

Table of contents

This article is a series of practical React components. Here, in this article, we are going to learn how to create Modal in your react components.

What is a modal?

A modal is a dialog box/popup window that is displayed on top of the current page.

So, without any further ado, let's start.

  1. Install the react-modal package in your terminal by running this command:

       $ npm install react-modal
    
  2. Let's create a simple react component.

So, let's elaborate on the above code.

Firstly, import the package.

    import Modal from "react-modal";

Define the state variables as,

    const [showModal, setShowModal] = useState(false);

On button click, the modal should be opened.

<button onClick={() => setShowModal(true)}>Display Modal</button>


      <Modal  isOpen={showModal}  onRequestClose={() => setShowModal(false)}
        style={
            {
              overlay: { backgroundColor: "grey" },
              content: {
                color: "blue"
              }
            }
          }>

            <h2>Modal opened</h2>
            <button onClick={() => setShowModal(false)}>Close Modal</button>
      </Modal>

You can define custom Inline styling for your modal as shown in the above code.

So, that's the way how we can simply make a modal with the help of a package.

You can make your own modal too.

You can find the sandbox for creating your own modal below.

That's it for today.

Thank you for reading through this article. I hope it provided a good understanding of how to create modals in your react components.

0
Subscribe to my newsletter

Read articles from Sabiya Tabassum directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sabiya Tabassum
Sabiya Tabassum

A frontend developer.