Kinda Code
Home/React/How to make a modal box from scratch in React

How to make a modal box from scratch in React

Last updated: March 03, 2023

The example below shows you how to create a modal dialog from scratch in ReactJS without any third-party libraries.

Table of Contents

  1. Preview
  2. The Code
  3. Conclusion

Preview

The sample app we’re going to build contains has a green button. When this button gets clicked, our modal dialog will show up. This modal has a title, some contents, and a close button. Here’s how it works:

The Code

Create a new React project, delete everything in App.js as well as App.css then add the following:

App.js

import React, { useState } from "react";
import "./App.css";

function App() {
  const [isOpen, setIsOpen] = useState(false);
  const openModal = () => {
    setIsOpen(true);
  }

  const closeModal = () => {
    setIsOpen(false);
  }

  return (
    <div className="App">
      {isOpen && (
        <>
          <div className="overlay"></div>
          <div className="modal">
            <header className="modal__header">
              <h2>Modal Title</h2>
              <button onClick={closeModal} className="close-button">&times;</button>
            </header>
            <main className="modal__main">
              <p>Some content here!</p>
            </main>
          </div>
        </>
      )}

      <h2>Just Some Dummy Text</h2>
      <button className="button" onClick={openModal}>Open Modal</button>
    </div>
  );
}

export default App;

App.css

.App {
  width: 90%;
  padding: 50px;
}

.overlay {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, .7);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10;
}

.modal {
  position: fixed;
  z-index: 20;
  background: #fff;
  width: 500px;

  /* Center the modal */
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

.modal__header {
  background: orangered;
  padding: 10px 20px;
  display: flex;
  justify-content: space-between;
}

.modal__main {
  padding: 20px;
}

.close-button {
  border: none;
  background: transparent;
  padding: 10px;
  cursor: pointer;
  color: #fff;
  font-size: 36px;
}

.close-button:hover {
  color: yellow;
}

.button {
  background: green;
  border: none;
  padding: 10px 20px;
  color: #fff;
  cursor: pointer;

}

.button:hover {
  background: orange;
}

Conclusion

We’ve examined a complete example of implementing a real-world-like modal from scratch. If you’d like to explore more new and interesting stuff about modern React, take a look at the following articles:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Related Articles