DEV Community

Cover image for Custom Modal React.js
Utsav Mavani
Utsav Mavani

Posted on

Custom Modal React.js

Exmaple-1:

To create a reusable and responsive custom modal in React.js that centers on screens with a minimum width of 768px and is positioned at the top 5% otherwise, you can follow these steps:

  1. Set up a new React project or use an existing one.

  2. Create a new component for your modal. You can name it CustomModal.js.

// CustomModal.js
import React from 'react';
import './CustomModal.css';

const CustomModal = ({ isOpen, onClose, children }) => {
  if (!isOpen) return null;

  return (
    <div className="custom-modal">
      <div className="custom-modal-content">
        <button className="close-button" onClick={onClose}>
          Close
        </button>
        {children}
      </div>
    </div>
  );
};

export default CustomModal;
Enter fullscreen mode Exit fullscreen mode
  • Create a CSS file for your modal styles. You can name it CustomModal.css.
/* CustomModal.css */
.custom-modal {
  position: fixed;
  top: 5%;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.6);
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  overflow: auto;
}

@media (min-width: 768px) {
  .custom-modal {
    top: 50%;
    transform: translate(-50%, -50%);
  }
}

.custom-modal-content {
  background: #fff;
  padding: 20px;
  border-radius: 5px;
  position: relative;
  max-width: 80%;
  width: 400px;
  max-height: 80%;
  overflow-y: auto;
}

.close-button {
  position: absolute;
  top: 10px;
  right: 10px;
  background: none;
  border: none;
  cursor: pointer;
}
Enter fullscreen mode Exit fullscreen mode
  • Create a parent component (e.g., App.js) where you'll use the CustomModal component.
// App.js
import React, { useState } from 'react';
import CustomModal from './CustomModal';

function App() {
  const [modalIsOpen, setModalIsOpen] = useState(false);

  const openModal = () => {
    setModalIsOpen(true);
  };

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

  return (
    <div className="App">
      <button onClick={openModal}>Open Modal</button>
      <CustomModal isOpen={modalIsOpen} onClose={closeModal}>
        <h2>Modal Content</h2>
        <p>This is a reusable custom modal.</p>
      </CustomModal>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now you have a responsive and reusable custom modal that centers on screens with a minimum width of 768px and is positioned at the top 5% for smaller screens. The you can close the modal by clicking the "Close" button or pressing the Escape key.

Top comments (0)