0
0
ReactHow-ToBeginner · 3 min read

How to Create a Modal in React: Simple Guide with Example

To create a modal in React, use a functional component with a useState hook to control its visibility. Render the modal conditionally based on state and include a button to open and close it.
📐

Syntax

A modal in React is typically a component that shows or hides content based on a boolean state. You use useState to track if the modal is open. The modal content is rendered only when this state is true. Buttons or events toggle this state to open or close the modal.

jsx
import React, { useState } from 'react';

function ModalExample() {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <>
      <button onClick={() => setIsOpen(true)}>Open Modal</button>
      {isOpen && (
        <div className="modal">
          <div className="modal-content">
            <button onClick={() => setIsOpen(false)}>Close</button>
            <p>This is the modal content.</p>
          </div>
        </div>
      )}
    </>
  );
}

export default ModalExample;
💻

Example

This example shows a simple modal that opens when you click the "Open Modal" button and closes when you click the "Close" button inside the modal. The modal uses basic CSS for overlay and content styling.

jsx
import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';

function Modal({ onClose }) {
  return (
    <div style={styles.overlay} aria-modal="true" role="dialog">
      <div style={styles.modal} tabIndex={-1}>
        <button onClick={onClose} aria-label="Close modal" style={styles.closeButton}>Close</button>
        <p>This is the modal content.</p>
      </div>
    </div>
  );
}

function App() {
  const [isModalOpen, setIsModalOpen] = useState(false);

  return (
    <div>
      <button onClick={() => setIsModalOpen(true)}>Open Modal</button>
      {isModalOpen && <Modal onClose={() => setIsModalOpen(false)} />}
    </div>
  );
}

const styles = {
  overlay: {
    position: 'fixed',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0,0,0,0.5)',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center'
  },
  modal: {
    backgroundColor: 'white',
    padding: '1rem 2rem',
    borderRadius: '8px',
    maxWidth: '400px',
    boxShadow: '0 2px 10px rgba(0,0,0,0.3)'
  },
  closeButton: {
    marginBottom: '1rem',
    cursor: 'pointer'
  }
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Output
A page with a button labeled "Open Modal". Clicking it shows a centered white box with text "This is the modal content." and a "Close" button. The background dims with a semi-transparent black overlay. Clicking "Close" hides the modal.
⚠️

Common Pitfalls

  • Not controlling modal visibility with state causes it to always show or never show.
  • Forgetting to add an overlay can confuse users about modal focus.
  • Not handling keyboard accessibility (like focus trap or Escape key) reduces usability.
  • Rendering modal inside normal flow can break layout; portals are better for complex apps.
jsx
import React, { useState } from 'react';

/* Wrong: Modal always visible without state control */
function WrongModal() {
  return (
    <div className="modal">
      <p>Modal always visible</p>
    </div>
  );
}

/* Right: Use state to toggle modal visibility */
function RightModal() {
  const [open, setOpen] = useState(false);
  return (
    <>
      <button onClick={() => setOpen(true)}>Open</button>
      {open && <div className="modal">Modal visible</div>}
    </>
  );
}
📊

Quick Reference

Tips for creating modals in React:

  • Use useState to track if modal is open.
  • Render modal conditionally based on state.
  • Include an overlay to focus user attention.
  • Provide buttons or actions to open and close modal.
  • Consider accessibility: ARIA roles, keyboard navigation.

Key Takeaways

Use React's useState hook to control modal visibility.
Render the modal component only when its open state is true.
Add an overlay and close button for better user experience.
Avoid rendering modal always; toggle it with state.
Consider accessibility by adding ARIA roles and keyboard support.