Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

reactjs
modal
communitycreator

How to create a Modal in React JS

Gautham Vijayan

Introduction

In this shot, we look into how we can create a Modal in React JS. Modals are extensively used in applications to alert users for Login/Signup purposes.

Installation

First, let’s create a new React JS project from the terminal.

npx create-react-app modalexample
cd modalexample

Now, let’s go to the terminal and run the following command to install the Modal to our React project.

npm i react-modal

We use Hooks to handle the state and show the Modal when we click the “Show Modal” button. We add our Modal in App.js.

import React, { useState } from "react";
import Modal from "react-modal";
const customStyles = {
  content: {
    top: "50%",
    left: "50%",
    right: "auto",
    bottom: "auto",
    marginRight: "-50%",
    transform: "translate(-50%, -50%)",
    backgroundColor: "white",
    width: 400,
  },
};

function App() {
  const [modalOpen, setModalOpen] = useState(false);

  return (
    <div className="App">
      <button onClick={setModalOpen}>Open Modal</button>
      <Modal
        isOpen={modalOpen}
        onRequestClose={() => setModalOpen(false)}
        style={customStyles}
      >
        <div>Login/Signup</div>

        <button onClick={() => setModalOpen(false)}>Close Modal</button>
      </Modal>
    </div>
  );
}

export default App;
Adding Modal to App.js

When we click the “Show Modal” button, a Modal pops out with the words “Login/Signup.” When we click the “Close Modal” button, the Modal closes. The Modal also closes when we click outside it. This adds to the UX aspect of our application.

In the custom styles, we can modify how our Modal looks. For example, we can change the background color of our Modal.

To integrate Modal into our React application, we create a useState value and attach it to our Modal. So, when we click on the button, the Boolean value will toggle and the Modal will appear/disappear.

RELATED TAGS

reactjs
modal
communitycreator
RELATED COURSES

View all Courses

Keep Exploring