How to create a reusable overlay in React Js

Last updated : September 12, 2022

This tutorial will show you how to create a reusable overlay in React Js. To make the overlay reusable and global in my application, I use a React portal to host my overlay. React portals live outside the components to make them more common to all the components in the application.

1. Create a placeholder to mount the overlay

Edit the index.html file in the public folder and add a div. My div id is modal.

    <div id="overlay"></div><!-- to mount the overlay -->
    <div id="root"></div><!-- to mount the app -->

2. Create a React component to render the overlay

Now I need a component to render the overlay. In this way, I can reuse my overlay for different purposes. Such as to show a modal or a loading indicator. I can hide the modal using the function passed in as a prop.

import { ReactNode } from "react"
import ReactDOM from 'react-dom';
import styles from "./Overlay.module.css"

interface OverlayProps {
    children: ReactNode
    hideOverlay: () => void
export const Overlay = (props: OverlayProps) => {
 return ReactDOM.createPortal(
    <div className={styles.overlay} onClick={props.hideOverlay}>{props.children}</div>, 

My overlay styles are in a CSS module called Overlay.module.css.

.overlay {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  z-index: 2;
  cursor: pointer;

It is simple as that. Now I have a reusable overlay that I can use in any component. Use the overlay component and pass any data you want to display.

import { useState } from "react"
import { Overlay } from "./components/overlay"

export const App = () => {

const [show, setShow] = useState<boolean>(false)

const showOverlay = () => {

const hideOverlay = () => {

      {show && 
      <Overlay hideOverlay={hideOverlay}>
        {/*Pass any data to the modal */}
      <button onClick={showOverlay}>Show Modal</button>
export default App
By: Lance
Lance is a software engineer with over 15 years of experience in full-stack software development.

Comments are disabled

No Comments