DEV Community

Kaziu
Kaziu

Posted on

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay