DEV Community

Cover image for How to Create Modal Popup in React JS
Shantanu Jana
Shantanu Jana

Posted on

How to Create Modal Popup in React JS

In this article you will learn how to create popup box using React. Earlier I have shared many popup window and automatic popup box tutorial using html css and javascript.

In React JS, you can create a Popup component that can be reused throughout your application.

The basic idea is to have a state variable that keeps track of whether the popup should be visible or not and a function that toggles this state.

Here's an example of how you can create a simple Popup component in React JS:

import React, { useState } from 'react';

function Popup({ children }) {
  const [isOpen, setIsOpen] = useState(false);
  return (
    <>
      <button onClick={() => setIsOpen(true)}>Open Popup</button>
      {isOpen && (
        <div className="popup">
          <div className="popup-content">
            {children}
            <button onClick={() => setIsOpen(false)}>Close</button>
          </div>
        </div>
      )}
    </>
  );
}

export default Popup;

Enter fullscreen mode Exit fullscreen mode

In this example, the Popup component uses the useState Hook to manage the state of the popup. It has a state variable isOpen that is initially set to false and a setIsOpen function that toggles the state.

The component renders a button that calls the setIsOpen function with a value of true when clicked, which opens the popup.

The component also renders the children passed to it, and a close button that calls the setIsOpen function with a value of false when clicked, which closes the popup.

You can use this component in other parts of your application by importing it and passing any content you want to display inside the Popup as children, like so:

import Popup from './Popup';

function App() {
  return (
    <Popup>
      <h2>Popup Title</h2>
      <p>Popup message goes here</p>
    </Popup>
  );
}

Enter fullscreen mode Exit fullscreen mode

The code you provided is an example of how you can use the Popup component in your application.

The App function renders the Popup component and passes any content you want to display inside the Popup as children.

It's important to note that this is a basic example and it's necessary to customize the design and functionality to fit your needs, also you can use some libraries like react-modal or react-overlays to have more powerful functionalities.

Top comments (0)