Categories
React Answers

How to Create a React Modal that Appends to the body Element?

Spread the love

Sometimes, we want to create a React modal that appends to the body element.

In this article, we’ll look at how to create a React modal that appends to the body element.

Create a React Modal that Appends to the body Element

To create a React modal that appends to the body element, we can use the react-portal package.

To install it, we run:

npm i react-portal

Then we write:

import { PortalWithState } from "react-portal";

export default function App() {
  return (
    <div>
      <PortalWithState closeOnOutsideClick closeOnEsc>
        {({ openPortal, closePortal, portal }) => (
          <>
            <button onClick={openPortal}>Open Portal</button>
            {portal(
              <p>
                hello world <button onClick={closePortal}>Close me!</button>,
              </p>
            )}
          </>
        )}
      </PortalWithState>
    </div>
  );
}

to add a modal with the PortalWithState component.

The closeOnOutsideClick prop lets us close the modal when we click outside it.

And the closeOnEsc prop lets us close the modal when we press the Esc key.

In the render prop function, we have the modal content in the argument of the portal function

The openPortal function lets us open the modal.

And the closePortal function closes the modal.

Conclusion

To create a React modal that appends to the body element, we can use the react-portal package.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *