Dialog
A window overlaid on either the primary window or another dialog window.
The Dialog component displays a modal overlay that appears on top of the main content. It includes a backdrop, close button, and supports keyboard navigation (Escape to close). Built from scratch using React and native HTML elements. No dependencies on any UI library.
Code
TypeScript: Copy this code into components/ui/dialog.tsx:
tsx
"use client"
import * as React from "react"
import * as ReactDOM from "react-dom"
import { cn } from "@/lib/utils"
interface DialogContextValue {
open: boolean
onOpenChange: (open: boolean) => void
}
const DialogContext = React.createContext<DialogContextValue | undefined>(undefined)
const useDialog = () => {
const context = React.useContext(DialogContext)
if (!context) {
throw new Error("Dialog components must be used within Dialog")
}
return context
}
interface DialogProps {
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
children: React.ReactNode
}
const Dialog = ({ open: controlledOpen, defaultOpen = false, onOpenChange, children }: DialogProps) => {
const [uncontrolledOpen, setUncontrolledOpen] = React.useState(defaultOpen)
const isControlled = controlledOpen !== undefined
const open = isControlled ? controlledOpen : uncontrolledOpen
const handleOpenChange = React.useCallback((newOpen: boolean) => {
if (!isControlled) {
setUncontrolledOpen(newOpen)
}
onOpenChange?.(newOpen)
}, [isControlled, onOpenChange])
React.useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === "Escape" && open) {
handleOpenChange(false)
}
}
document.addEventListener("keydown", handleEscape)
return () => document.removeEventListener("keydown", handleEscape)
}, [open, handleOpenChange])
React.useEffect(() => {
if (open) {
document.body.style.overflow = "hidden"
} else {
document.body.style.overflow = ""
}
return () => {
document.body.style.overflow = ""
}
}, [open])
return (
<DialogContext.Provider value={{ open, onOpenChange: handleOpenChange }}>
{children}
</DialogContext.Provider>
)
}
interface DialogTriggerProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
asChild?: boolean
}
const DialogTrigger = React.forwardRef<HTMLButtonElement, DialogTriggerProps>(
({ className, children, onClick, asChild, ...props }, ref) => {
const { onOpenChange } = useDialog()
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
onOpenChange(true)
onClick?.(e)
}
if (asChild && React.isValidElement(children)) {
return React.cloneElement(children, {
onClick: handleClick,
ref,
...props,
} as any)
}
return (
<button
ref={ref}
onClick={handleClick}
className={className}
{...props}
>
{children}
</button>
)
}
)
DialogTrigger.displayName = "DialogTrigger"
const DialogContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, children, ...props }, ref) => {
const { open, onOpenChange } = useDialog()
if (!open) return null
const handleBackdropClick = (e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === e.currentTarget) {
onOpenChange(false)
}
}
const content = (
<div
className="fixed inset-0 z-50 flex items-center justify-center"
onClick={handleBackdropClick}
>
<div className="fixed inset-0 bg-black/50" />
<div
ref={ref}
className={cn(
"relative z-50 w-full max-w-lg rounded-lg border-2 border-foreground bg-background p-6 neobrutalism-shadow",
className
)}
onClick={(e) => e.stopPropagation()}
{...props}
>
{children}
</div>
</div>
)
return ReactDOM.createPortal(content, document.body)
})
DialogContent.displayName = "DialogContent"
const DialogHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 text-center sm:text-left mb-4", className)}
{...props}
/>
))
DialogHeader.displayName = "DialogHeader"
const DialogTitle = React.forwardRef<
HTMLHeadingElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h2
ref={ref}
className={cn("text-lg font-bold leading-none tracking-tight", className)}
{...props}
/>
))
DialogTitle.displayName = "DialogTitle"
const DialogDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = "DialogDescription"
const DialogFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2 mt-6", className)}
{...props}
/>
))
DialogFooter.displayName = "DialogFooter"
const DialogClose = React.forwardRef<
HTMLButtonElement,
React.ButtonHTMLAttributes<HTMLButtonElement>
>(({ className, onClick, ...props }, ref) => {
const { onOpenChange } = useDialog()
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
onOpenChange(false)
onClick?.(e)
}
return (
<button
ref={ref}
onClick={handleClick}
className={cn(
"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",
className
)}
{...props}
>
<svg
className="h-4 w-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M6 18L18 6M6 6l12 12"
/>
</svg>
<span className="sr-only">Close</span>
</button>
)
})
DialogClose.displayName = "DialogClose"
export {
Dialog,
DialogTrigger,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
DialogClose,
}JavaScript: Copy this code into components/ui/dialog.jsx:
jsx
"use client"
import * as React from "react"
import * as ReactDOM from "react-dom"
import { cn } from "@/lib/utils"
const DialogContext = React.createContext(undefined)
const useDialog = () => {
const context = React.useContext(DialogContext)
if (!context) {
throw new Error("Dialog components must be used within Dialog")
}
return context
}
const Dialog = ({ open: controlledOpen, defaultOpen = false, onOpenChange, children }) => {
const [uncontrolledOpen, setUncontrolledOpen] = React.useState(defaultOpen)
const isControlled = controlledOpen !== undefined
const open = isControlled ? controlledOpen : uncontrolledOpen
const handleOpenChange = React.useCallback((newOpen) => {
if (!isControlled) {
setUncontrolledOpen(newOpen)
}
onOpenChange?.(newOpen)
}, [isControlled, onOpenChange])
React.useEffect(() => {
const handleEscape = (e) => {
if (e.key === "Escape" && open) {
handleOpenChange(false)
}
}
document.addEventListener("keydown", handleEscape)
return () => document.removeEventListener("keydown", handleEscape)
}, [open, handleOpenChange])
React.useEffect(() => {
if (open) {
document.body.style.overflow = "hidden"
} else {
document.body.style.overflow = ""
}
return () => {
document.body.style.overflow = ""
}
}, [open])
return (
<DialogContext.Provider value={{ open, onOpenChange: handleOpenChange }}>
{children}
</DialogContext.Provider>
)
}
const DialogTrigger = React.forwardRef(
({ className, children, onClick, asChild, ...props }, ref) => {
const { onOpenChange } = useDialog()
const handleClick = (e) => {
onOpenChange(true)
onClick?.(e)
}
if (asChild && React.isValidElement(children)) {
return React.cloneElement(children, {
onClick: handleClick,
ref,
...props,
})
}
return (
<button
ref={ref}
onClick={handleClick}
className={className}
{...props}
>
{children}
</button>
)
}
)
DialogTrigger.displayName = "DialogTrigger"
const DialogContent = React.forwardRef(
({ className, children, ...props }, ref) => {
const { open, onOpenChange } = useDialog()
if (!open) return null
const handleBackdropClick = (e) => {
if (e.target === e.currentTarget) {
onOpenChange(false)
}
}
const content = (
<div
className="fixed inset-0 z-50 flex items-center justify-center"
onClick={handleBackdropClick}
>
<div className="fixed inset-0 bg-black/50" />
<div
ref={ref}
className={cn(
"relative z-50 w-full max-w-lg rounded-lg border-2 border-foreground bg-background p-6 neobrutalism-shadow",
className
)}
onClick={(e) => e.stopPropagation()}
{...props}
>
{children}
</div>
</div>
)
return ReactDOM.createPortal(content, document.body)
}
)
DialogContent.displayName = "DialogContent"
const DialogHeader = React.forwardRef(
({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 text-center sm:text-left mb-4", className)}
{...props}
/>
)
)
DialogHeader.displayName = "DialogHeader"
const DialogTitle = React.forwardRef(
({ className, ...props }, ref) => (
<h2
ref={ref}
className={cn("text-lg font-bold leading-none tracking-tight", className)}
{...props}
/>
)
)
DialogTitle.displayName = "DialogTitle"
const DialogDescription = React.forwardRef(
({ className, ...props }, ref) => (
<p
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
)
DialogDescription.displayName = "DialogDescription"
const DialogFooter = React.forwardRef(
({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2 mt-6", className)}
{...props}
/>
)
)
DialogFooter.displayName = "DialogFooter"
const DialogClose = React.forwardRef(
({ className, onClick, ...props }, ref) => {
const { onOpenChange } = useDialog()
const handleClick = (e) => {
onOpenChange(false)
onClick?.(e)
}
return (
<button
ref={ref}
onClick={handleClick}
className={cn(
"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",
className
)}
{...props}
>
<svg
className="h-4 w-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M6 18L18 6M6 6l12 12"
/>
</svg>
<span className="sr-only">Close</span>
</button>
)
}
)
DialogClose.displayName = "DialogClose"
export {
Dialog,
DialogTrigger,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
DialogClose,
}Usage
TypeScript:
tsx
import {
Dialog,
DialogTrigger,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
DialogClose,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { useState } from "react"
function MyComponent() {
const [open, setOpen] = useState(false)
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button>Edit Profile</Button>
</DialogTrigger>
<DialogContent>
<DialogClose />
<DialogHeader>
<DialogTitle>Edit profile</DialogTitle>
<DialogDescription>
Configure your Things component library settings here. Click save when you're done.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<label htmlFor="name" className="text-sm font-bold">Name</label>
<Input id="name" defaultValue="Pranav Murali" />
</div>
<div className="space-y-2">
<label htmlFor="username" className="text-sm font-bold">Username</label>
<Input id="username" defaultValue="@marvellousz" />
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button onClick={() => setOpen(false)}>
Save changes
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}JavaScript:
jsx
import {
Dialog,
DialogTrigger,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
DialogClose,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { useState } from "react"
function MyComponent() {
const [open, setOpen] = useState(false)
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button>Edit Profile</Button>
</DialogTrigger>
<DialogContent>
<DialogClose />
<DialogHeader>
<DialogTitle>Edit profile</DialogTitle>
<DialogDescription>
Configure your Things component library settings here. Click save when you're done.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<label htmlFor="name" className="text-sm font-bold">Name</label>
<Input id="name" defaultValue="Pranav Murali" />
</div>
<div className="space-y-2">
<label htmlFor="username" className="text-sm font-bold">Username</label>
<Input id="username" defaultValue="@marvellousz" />
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button onClick={() => setOpen(false)}>
Save changes
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}Make sure you also have the lib/utils.ts file with the cn helper function, and the required UI components (button, input).