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.
Edit the index.html file in the public folder and add a div. My div id is modal.
<body>
<div id="overlay"></div><!-- to mount the overlay -->
<div id="root"></div><!-- to mount the app -->
</body>
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>,
document.getElementById("overlay")!)
}
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 = () => {
setShow(true)
}
const hideOverlay = () => {
setShow(false)
}
return(
<>
{show &&
<Overlay hideOverlay={hideOverlay}>
{/*Pass any data to the modal */}
</Overlay>
}
<button onClick={showOverlay}>Show Modal</button>
</>
)
}
export default App