useDialog

Provides imperative APIs to open different types of dialogs (alert, confirm, prompt) or custom dialogs.

Usage

Install CustomProvider

The first thing you need to do is install CustomProvider at the root of your application to manage the dialog rendering container.

import { CustomProvider } from 'rsuite';

function App({ children }) {
  return <CustomProvider>{children}</CustomProvider>;
}

Using useDialog

import { useDialog } from 'rsuite';

function MyApp() {
  const dialog = useDialog();

  // Alert dialog
  dialog.alert('Hello, world!');

  // Confirm dialog
  dialog.confirm('Are you sure?');

  // Prompt dialog
  dialog.prompt('What is your name?');

  // Custom dialog
  dialog.open(CustomDialog);
}

Examples

Alert Dialog

Similar to window.alert, it opens a dialog to display a message to the user.

Confirm Dialog

Similar to window.confirm, it opens a dialog to ask the user a question.

Prompt Dialog

Similar to window.prompt, it opens a dialog to ask the user to input some text.

Prompt Dialog with Validation

You can add validation to prompt dialogs to ensure the input meets certain criteria before allowing the user to proceed.

Custom Dialog

Displays a custom dialog component.

Stacked Dialogs

API

useDialog()

Returns an object containing the following methods:

Property Type Description
alert (message: ReactNode, options?: AlertOptions) => Promise<void> Shows an alert dialog
confirm (message: ReactNode, options?: ConfirmOptions) => Promise<boolean> Shows a confirmation dialog
prompt (message: ReactNode, options?: PromptOptions) => Promise<string> Shows a prompt dialog
open (component: ComponentType, payload?: P, options?: OpenOptions) => Promise<T> Shows a custom dialog

Type Definitions

AlertOptions

interface AlertOptions {
  title?: string; // Dialog title, defaults to 'Alert'
  okText?: string; // Text for the OK button, defaults to 'OK'
  onClose?: () => void; // Callback when dialog is closed
}

ConfirmOptions

interface ConfirmOptions {
  title?: string; // Dialog title, defaults to 'Confirm'
  okText?: string; // Text for the OK button, defaults to 'OK'
  cancelText?: string; // Text for the Cancel button
  severity?: 'info' | 'success' | 'warning' | 'error'; // Visual style of the dialog
  onClose?: (result: boolean) => void; // Callback when dialog is closed
}

PromptOptions

interface PromptOptions {
  title?: string; // Dialog title, defaults to 'Confirm'
  okText?: string; // Text for the OK button, defaults to 'OK'
  cancelText?: string; // Text for the Cancel button
  defaultValue?: string; // Default value for the input field
  validate?: (value: string) => [isValid: boolean, errorMessage?: string]; // Validation function
  onClose?: (result: string) => void; // Callback when dialog is closed
}

OpenOptions

interface OpenOptions<T> {
  onClose?: (result?: T) => void; // Callback when dialog is closed
}