Building Modals in React

Anthony Panagi
The Startup
Published in
4 min readJun 22, 2020

--

Intro

Modals (aka overlays, dialogs, etc.) are a ubiquitous part of web and app development. An elegant solution to alerting a user while on the same page by simplifying the UI and saving screen real estate. That being said, a modal is inherently disruptive to UX so make sure it is serving a purpose and the user is ultimately better off for it.

What we are trying to achieve

Modals can be notoriously difficult to implement in React due to the way the DOM is structured. In a nutshell, your React app is essentially one large component with a bunch of child components that sit within it. This means that in even a pretty simple app, components can get very deeply nested.

In the past, if one of those deeply nested components needed to render a component (modal, in our case) above all parent components, it would require some hacky CSS tricks to work. Lucky for us, React 16 introduced Portalsan elegant solution to rendering children into a DOM node that exists outside the DOM hierarchy of the parent component.

Code

So let’s look at how we implement a modal system using Portals.

First, we need to create a custom React hook that will power our modal. Create a file called useModal.js

import { useState } from 'react';const useModal = () => {
const

--

--