Skip to content

useDialogBox

Hook to use Dialog Box prompt, alert or confirm.

Demo

INFO

The component renders three button that execute three useDialogBox hook with a type for each one.

Loading demo…
Show source code
tsx
import { useState } from "react";
import { useDialogBox } from "../../../.."

export const UseDialogBox = () => {
	const [response, setResponse] = useState("");
	const openPrompt = useDialogBox("prompt");
	const openAlert = useDialogBox("alert");
	const openConfirm = useDialogBox("confirm");

	return <div style={{ display: 'flex', flexDirection: "column", justifyContent: "center" }}>
		<p>Response: {response}</p>
		<div style={{ display: 'flex', gap: 10, justifyContent: "center" }}>
			<button
				onClick={() => {
					const resp = openPrompt("Are you open a prompt?");
					setResponse(resp!);
				}}
			>
				Open Prompt
			</button>
			<button
				onClick={() => {
					openAlert("You open a alert");
				}}
			>
				Open Alert
			</button>
			<button
				onClick={() => {
					const resp = openConfirm("You open a confirm. it's ok?");
					setResponse(resp ? "ok" : "ko");
				}}
			>
				Open Confirm
			</button>
		</div>
	</div>
}

Types

DialogType

The possible types for the native dialog box.

ts
export type DialogType = "prompt" | "alert" | "confirm";

PromptHandler

Function that triggers a native window.prompt.

ts
export type PromptHandler = (message?: string, _default?: string) => string | null;

AlertHandler

Function that triggers a native window.alert.

ts
export type AlertHandler = (message?: any) => void;

ConfirmHandler

Function that triggers a native window.confirm.

ts
export type ConfirmHandler = (message?: string) => boolean;

DialogHandler

Union of all possible handler functions returned by the hook.

ts
export type DialogHandler = PromptHandler | AlertHandler | ConfirmHandler;

Released under the MIT License.