Overlay
An Overlay
is an element that normally covers the entire screen and prevents
content behind it from being interactable.
Simple Overlay
An Overlay
dynamically renders itself based on a visible
prop with a simple
opacity transition. An Overlay
should normally have an onClick
handler that
hide the overlay.
"use client";
import { Button } from "@react-md/core/button/Button";
import { Overlay } from "@react-md/core/overlay/Overlay";
import { useToggle } from "@react-md/core/useToggle";
import { type ReactElement } from "react";
export default function SimpleOverlayExample(): ReactElement {
const { toggled, enable, disable } = useToggle();
return (
<>
<Button onClick={enable}>Show Overlay</Button>
<Overlay visible={toggled} onClick={disable} />
</>
);
}
Invisible Overlay
If the Overlay
should be rendered with another element and act as a way to
"close on outside click" without clicking other elements, enable the noOpacity
prop.
"use client";
import { DropdownMenu } from "@react-md/core/menu/DropdownMenu";
import { MenuItem } from "@react-md/core/menu/MenuItem";
import { Overlay } from "@react-md/core/overlay/Overlay";
import { type ReactElement, useState } from "react";
// Try clicking on an item in the `TableOfContents` with and without the overlay
export default function InvisibleOverlayExample(): ReactElement {
const [visible, setVisible] = useState(false);
return (
<DropdownMenu
buttonChildren="Dropdown"
visible={visible}
setVisible={setVisible}
>
<Overlay
visible
noOpacity
onClick={() => {
setVisible(false);
}}
/>
<MenuItem>Item 1</MenuItem>
<MenuItem>Item 2</MenuItem>
<MenuItem>Item 3</MenuItem>
</DropdownMenu>
);
}
Overlay with Content
The Overlay
can also render children
if and supports the box align-items
and justify-content
.
"use client";
import { Button } from "@react-md/core/button/Button";
import { cssUtils } from "@react-md/core/cssUtils";
import { List } from "@react-md/core/list/List";
import { ListItem } from "@react-md/core/list/ListItem";
import { Overlay } from "@react-md/core/overlay/Overlay";
import { ScrollLock } from "@react-md/core/scroll/ScrollLock";
import { useToggle } from "@react-md/core/useToggle";
import { type ReactElement } from "react";
export default function OverlayWithContentExample(): ReactElement {
const { toggled, enable, disable } = useToggle();
return (
<>
<Button onClick={enable}>Show</Button>
<Overlay
visible={toggled}
onClick={disable}
align="start"
justify="space-around"
>
<ScrollLock />
<List className={cssUtils({ backgroundColor: "surface" })}>
<ListItem>Item 1</ListItem>
<ListItem>Item 2</ListItem>
<ListItem>Item 3</ListItem>
</List>
<List className={cssUtils({ backgroundColor: "surface" })}>
<ListItem>Item 1</ListItem>
<ListItem>Item 2</ListItem>
<ListItem>Item 3</ListItem>
</List>
</Overlay>
</>
);
}