iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🚀

Implementing a Reusable Modal with React Portal

に公開

This time, I tried implementing a reusable Modal using React's Portal to replace
commonly used modals!

Here is the repository I implemented this time ↓
https://github.com/YuukiHayashi0510/React-portal_practice

Benefits of Portal

I believe React's Portal has the following benefits:

  • Styles are isolated, so they are not affected by external styles.
  • It moves directly under document.body, allowing it to be rendered outside the component tree.
    • Suitable for modals and toasts.

With that in mind, I will implement a reusable Modal using Portal!

Approach

The approach for this project is as follows:

  1. Create a common component
  2. Implement a Provider to manage the Modal with Portal
  3. Call useModal
  4. Verify operation

I am using Tailwind CSS and Next.js.

Creating the Common Component

We'll skip the step-by-step creation for now and proceed assuming we use something like the following.
For the styling, I've used what's built into Tailwind for now, creating only the overlay and the modal frame.

~components/Modal.tsx
import { memo } from 'react'

type Props = React.PropsWithChildren<{ onClose: () => void }>

export const Modal = memo<Props>(({ children, onClose }) => {
  return (
    <div
      className='fixed left-0 top-0 z-10 flex h-full w-full items-center justify-center overflow-auto bg-gray-900 bg-opacity-50'
      onClick={onClose}
    >
      <div
        className='relative inline-block origin-top-left rounded-lg bg-white p-5 shadow-xl'
        onClick={(e) => e.stopPropagation()}
      >
        {children}
      </div>
    </div>
  )
})

Modal.displayName = 'Modal'

Implementing the Provider to Manage Modals via Portal

Using this Provider, we will pass functions to open and close modals to the components nested under it.

The state required within the Provider is:

  1. Modal open/close status
  2. Modal content
  3. Modal className

The modal content and className are passed through the openModal function.
Also, since I want to reset the content and className when the modal closes, I implemented it to reset them inside closeModal.
If you want to create events like onOpen or onClose, you would likely either pass them through functions or add them to the Context.

~/providers/ModalProvider.tsx
import React, { PropsWithChildren, ReactNode, createContext, useContext, useState } from 'react'
import { createPortal } from 'react-dom'

import Modal from '../components/Modal'

type Context = {
  isOpen: boolean
  openModal: (content: ReactNode, className?: string) => void
  closeModal: () => void
}

const ModalContext = createContext({} as Context)

export const ModalProvider = ({ children }: PropsWithChildren) => {
  const [isOpen, setIsOpen] = useState(false)
  const [content, setContent] = useState<ReactNode>(null)
  const [className, setClassName] = useState<string>('')

  const openModal: Context['openModal'] = (content, className) => {
    setClassName(className ?? '')
    setContent(content)
    setIsOpen(true)
  }

  const closeModal: Context['closeModal'] = () => {
    setClassName('')
    setContent(null)
    setIsOpen(false)
  }

  return (
    <ModalContext.Provider
      value={{
        isOpen,
        openModal,
        closeModal,
      }}
    >
      {children}
      {isOpen
        ? createPortal(
            <Modal onClose={closeModal} className={className}>
              {content}
            </Modal>,
            document.body,
          )
        : null}
    </ModalContext.Provider>
  )
}

export const useModal = () => useContext(ModalContext)

And then, integrate the completed Provider into layout.tsx.

app/layout.tsx
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import './globals.css'
import { ModalProvider } from '~/providers/ModalProvider'

const inter = Inter({ subsets: ['latin'] })

export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang='en'>
      <body className={inter.className}>
        <ModalProvider>{children}</ModalProvider>
      </body>
    </html>
  )
}

Calling useModal

Call useModal in components under the Provider as shown below to retrieve functions for controlling the modal. Pass the modal content to openModal.

app/page.tsx
'use client'

import { useModal } from '~/providers/ModalProvider'
import ModalContent from './components/ModalContent'

export default function Home() {
  const { openModal, closeModal } = useModal()

  return (
    <main className='flex min-h-screen flex-col items-center justify-between p-24'>
      <button
        className='rounded border bg-white px-3 py-1'
        onClick={() => openModal(<ModalContent onClose={closeModal} />)}
      >
        Open Modal
      </button>
    </main>
  )
}

The content of ModalContent is as follows.
Since modals are often closed using buttons within the modal itself, I have prepared the following implementation as a sample.

app/components/ModalContent.tsx
import { Modal } from '~/components/Modal'

export default function ModalContent({ onClose }: { onClose: () => void }) {
  return (
    <Modal onClose={onClose}>
      <div>I&rsquo;m a modal dialog</div>
      <button className='rounded border px-2 py-1' onClick={onClose}>
        Close
      </button>
    </Modal>
  )
}

Operation Check

Let's check it by starting the Next.js server...


It was successfully implemented!

Toasts can be implemented in the same way. By setting CSS transitions and animations such as display duration and fade-ins, you can bring them closer to the toasts found in various libraries!

Let's keep building UIs using React's convenient APIs!
Great job!

References

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

Discussion