Modal with ReactDOM.createPortal

kaziusan

Kaziu

Posted on November 20, 2024

Modal with ReactDOM.createPortal

https://react.dev/reference/react-dom/createPortal

What is that

We can specify DOM element for rendering

When we could use it

For example, If we want to write <Modal /> component in some component, but want to rendering other parent component (ex. document.body)

We could write Modal, Popover component easily ignoring parent CSS effect like overflow: hidden.

And no matter what it is, easy to read code.

Example

this is example that modal opens center of window by using createPortal

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

function Modal({ isOpen, onClose, children }) {
  if (!isOpen) return null;

  return ReactDOM.createPortal(
    <div style={styles.overlay}>
      <div style={styles.modal}>
        {children}
        <button onClick={onClose} style={styles.closeButton}>Close</button>
      </div>
    </div>,
    document.body // ⭐️ the rendering destination of Portal
  );
}

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

  return (
    <div>
      <button onClick={() => setIsModalOpen(true)}>Open Modal</button>
      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)}>
        <h1>Hello, Modal!</h1>
      </Modal>
    </div>
  );
}

const styles = {
  overlay: {
    ⭐️ position: 'fixed',
    ⭐️ top: 0,
    ⭐️ left: 0,
    ⭐️ width: '100vw',
    ⭐️ height: '100vh',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 1000,
  },
  modal: {
    ...
  },
  closeButton: {
    ...
  },
};
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
kaziusan
Kaziu

Posted on November 20, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related