How to make a modal box from scratch in React

Updated: March 3, 2023 By: Napoleon Post a comment

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


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:


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

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

  const closeModal = () => {

  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>
            <main className="modal__main">
              <p>Some content here!</p>

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

export default App;


.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;


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.

Notify of
Inline Feedbacks
View all comments

Related Articles