Synertech Web/ui v0.57.5 Site Storybook

Documentation / Feedback & overlays

Modal

Client@synertech/uiOpen in Storybook

The library’s modal dialog: a header (title, description, icon), free content and a footer with the Confirm / Cancel buttons. It is controlled: you hold isOpen (or open, the name Drawer gives it) and set it back to false in onClose.

Both footer buttons call their handler and then close the modal. A promise is awaited, the buttons disabled meanwhile. The modal stays open when the handler returns false or throws: a form that does not validate, or a server that refuses, does not cost what was typed. onSubmitError receives the error; closeOnSubmit={false} leaves closing to the application.

The accessibility of a real modal comes from useDialogA11y: role="dialog" + aria-modal, accessible name taken from the title, initial focus, contained Tab, Escape, focus returned to the trigger, inert background and locked scrolling. Nested modals stack: only the topmost one reacts to the keyboard. A "use client" component.

The modal is rendered under <body>, not where it is declared: it can be opened from a Drawer or a mobile Sidebar, declared inside them or beside them, without being born in the part of the page they made inert.

The default labels (Confirm, Cancel, Close…) come from UILabelsProvider; the submitLabel, cancelLabel and closeLabel props take precedence over it.

Examples

Basic usage

The open state lives with the caller; onClose is called by the close button, Escape and the footer button.

Open in a tab
import { useState } from "react";
import { Button, Modal } from "@synertech/ui";

export function Basic() {
  const [open, setOpen] = useState(false);

  return (
    <>
      <Button onClick={() => setOpen(true)}>Ouvrir la modale</Button>
      <Modal isOpen={open} onClose={() => setOpen(false)} title="Bienvenue" submitLabel="Compris">
        <p className="text-gray-600">
          Votre espace est prêt. Vous pouvez inviter votre équipe dès maintenant.
        </p>
      </Modal>
    </>
  );
}

Confirming a destructive action

showCancel adds the Cancel button; submitClassName recolours the confirmation, size="sm" narrows the dialog.

Open in a tab
import { useState } from "react";
import { Button, Modal } from "@synertech/ui";

const TrashIcon = () => (
  <svg
    className="h-6 w-6 text-red-600"
    fill="none"
    viewBox="0 0 24 24"
    stroke="currentColor"
    strokeWidth={2}
    aria-hidden="true"
  >
    <path
      strokeLinecap="round"
      strokeLinejoin="round"
      d="M19 7l-.87 12.14A2 2 0 0116.14 21H7.86a2 2 0 01-1.99-1.86L5 7m5 4v6m4-6v6M9 7V4a1 1 0 011-1h4a1 1 0 011 1v3M4 7h16"
    />
  </svg>
);

export function ConfirmDelete() {
  const [open, setOpen] = useState(false);

  return (
    <>
      <Button bgColor="bg-red-600 hover:bg-red-700" onClick={() => setOpen(true)}>
        Supprimer le projet
      </Button>
      <Modal
        isOpen={open}
        onClose={() => setOpen(false)}
        size="sm"
        icon={<TrashIcon />}
        title="Supprimer le projet ?"
        description="Cette action est définitive."
        showCancel
        submitLabel="Supprimer"
        cancelLabel="Annuler"
        onSubmitClick={() => console.log("Projet supprimé")}
        submitClassName="bg-red-600 hover:bg-red-700 focus:ring-red-300"
      >
        <p className="text-sm text-gray-600">
          Les 42 tâches et leurs pièces jointes seront perdues.
        </p>
      </Modal>
    </>
  );
}

Form with an async action

An onSubmitClick that returns a promise is awaited, the buttons disabled. When it returns false the modal stays open: confirm without a name to see it. initialFocus puts the cursor in the field.

Open in a tab
import { useRef, useState } from "react";
import { Button, Input, Modal } from "@synertech/ui";

export function FormModal() {
  const [open, setOpen] = useState(false);
  const [name, setName] = useState("");
  const [invalid, setInvalid] = useState(false);
  const nameRef = useRef<HTMLInputElement>(null);

  const save = async () => {
    if (name.trim() === "") {
      setInvalid(true);
      nameRef.current?.focus();
      return false;
    }

    await new Promise((resolve) => setTimeout(resolve, 800));
    console.log("Équipe créée :", name);
    setName("");
  };

  return (
    <>
      <Button onClick={() => setOpen(true)}>Nouvelle équipe</Button>
      <Modal
        isOpen={open}
        onClose={() => setOpen(false)}
        title="Créer une équipe"
        initialFocus={nameRef}
        showCancel
        submitLabel="Créer"
        onSubmitClick={save}
      >
        <Input
          ref={nameRef}
          label="Nom de l’équipe"
          value={name}
          error={invalid}
          helperText={invalid ? "Donnez un nom à l’équipe." : undefined}
          onChange={(event) => {
            setName(event.target.value);
            setInvalid(false);
          }}
        />
      </Modal>
    </>
  );
}

A save that fails

The handler throws: the modal stays open and onSubmitError receives the error. Here the first attempt fails and the second goes through.

Open in a tab
import { useRef, useState } from "react";
import { Button, Modal } from "@synertech/ui";

export function FailedSave() {
  const [open, setOpen] = useState(false);
  const [failure, setFailure] = useState<string>();
  const attempts = useRef(0);

  const publish = async () => {
    setFailure(undefined);
    await new Promise((resolve) => setTimeout(resolve, 600));
    attempts.current += 1;
    if (attempts.current === 1) throw new Error("Le serveur n’a pas répondu.");
  };

  return (
    <>
      <Button onClick={() => setOpen(true)}>Publier l’article</Button>
      <Modal
        open={open}
        onClose={() => setOpen(false)}
        size="sm"
        title="Publier l’article ?"
        showCancel
        submitLabel="Publier"
        onSubmitClick={publish}
        onSubmitError={(error) =>
          setFailure(error instanceof Error ? error.message : "La publication a échoué.")
        }
      >
        <p className="text-sm text-gray-600 dark:text-gray-300">
          L’article sera visible de tous les lecteurs.
        </p>
        {failure && (
          <p role="alert" className="text-sm text-red-600 dark:text-red-300">
            {failure} Réessayez.
          </p>
        )}
      </Modal>
    </>
  );
}

Footer and full screen

buttonsPosition aligns the buttons, reverseButtons reverses their order and allowFullScreen adds the expand button.

Open in a tab
import { useState } from "react";
import { Button, Modal } from "@synertech/ui";

export function LayoutOptions() {
  const [open, setOpen] = useState(false);

  return (
    <>
      <Button onClick={() => setOpen(true)}>Lire les conditions</Button>
      <Modal
        isOpen={open}
        onClose={() => setOpen(false)}
        size="lg"
        title="Conditions générales"
        allowFullScreen
        showCancel
        buttonsPosition="center"
        reverseButtons
        submitLabel="J’accepte"
        cancelLabel="Plus tard"
        showFooterDivider={false}
      >
        <p className="text-gray-600">
          Article 1 — Objet. Les présentes conditions régissent l’utilisation du service…
        </p>
      </Modal>
    </>
  );
}

No footer and no visible title

showSubmit={false} removes the footer; with title="", give an aria-label to name the dialog.

Open in a tab
import { useState } from "react";
import { Button, Modal } from "@synertech/ui";

export function ContentOnly() {
  const [open, setOpen] = useState(false);

  return (
    <>
      <Button onClick={() => setOpen(true)}>Voir l’aperçu</Button>
      <Modal
        isOpen={open}
        onClose={() => setOpen(false)}
        title=""
        aria-label="Aperçu de l’image"
        showSubmit={false}
        showHeaderDivider={false}
      >
        <img
          src="https://picsum.photos/640/360"
          alt="Paysage de montagne"
          className="w-full rounded-md"
        />
      </Modal>
    </>
  );
}

API reference

Components

ComponentClient
import { Modal } from "@synertech/ui";

Props — ModalProps

PropTypeDefaultDescription

+ 2 inherited native attributes from RefAttributes, Attributes (className, id, aria-*, event handlers…).