Modal

Modal dialogs.

Examples

Basic

<Button type="primary" on:click="{showModal}">Open Modal</Button>
<Modal
  title="Basic Modal"
  {visible}
  on:ok="{openAnother}"
  on:cancel="{closeModal}">
  <p>Some contents...</p>
  <p>Some contents...</p>
  <p>Some contents...</p>
</Modal>

<script>
  import { Modal, Button } from "svant";

  let visible = false;

  function showModal() {
    visible = true;
  }

  function closeModal() {
    visible = false;
  }

  function openAnother() {
    Modal.confirm({
      content: "Are you sure?",
      onOk: () => {
        closeModal();
      }
    });
  }
</script>

Asynchronously Close

Asynchronously close a modal dialog when a the OK button is pressed. For example, you can use this pattern when you submit a form.

<Button type="primary" on:click="{showModal}">
  Open Modal with async logic
</Button>
<Modal
  title="Title"
  {visible}
  on:ok="{handleOk}"
  {confirmLoading}
  on:cancel="{handleCancel}">
  <p>{ModalText}</p>
</Modal>

<script>
  import { Modal, Button } from "svant";

  let visible = false;
  let ModalText = "Content of the modal";
  let confirmLoading = false;

  function showModal() {
    visible = true;
  }

  function handleOk() {
    ModalText = "The modal will be closed after two seconds";
    confirmLoading = true;

    setTimeout(() => {
      visible = false;
      confirmLoading = false;
      ModalText = "Content of the modal";
    }, 2000);
  }

  function handleCancel() {
    console.log("Cancel button pressed");
    visible = false;
  }
</script>

Confirmation Modal Dialog

Use Modal.confirm() to show a confirmation modal dialog. The onOk and onCancel buttons can return a promise and will delay the modal from closing until completed.

<Button on:click="{showConfirm}">Confirm</Button>
<Button on:click="{showDeleteConfirm}" type="dashed">Delete</Button>
<Button on:click="{showPropsConfirm}" type="dashed">With extra props</Button>
<Button on:click="{showPromiseConfirm}">Confirm with Promise</Button>

<script>
  import { Button, Modal } from "svant";
  import { ExclamationCircleOutlined } from "svant/icons";

  const { confirm } = Modal;

  function showConfirm() {
    confirm({
      title: "Do you want to delete these items?",
      icon: ExclamationCircleOutlined,
      content: "Some descriptions",
      onOk() {
        console.log("OK");
      },
      onCancel() {
        console.log("Cancel");
      }
    });
  }

  function showDeleteConfirm() {
    confirm({
      title: "Are you sure delete this task?",
      icon: ExclamationCircleOutlined,
      content: "Some descriptions",
      okText: "Yes",
      okType: "danger",
      cancelText: "No",
      onOk() {
        console.log("OK");
      },
      onCancel() {
        console.log("Cancel");
      }
    });
  }

  function showPropsConfirm() {
    confirm({
      title: "Are you sure delete this task?",
      icon: ExclamationCircleOutlined,
      content: "Some descriptions",
      okText: "Yes",
      okType: "danger",
      okButtonProps: {
        disabled: true
      },
      cancelText: "No",
      onOk() {
        console.log("OK");
      },
      onCancel() {
        console.log("Cancel");
      }
    });
  }

  function showPromiseConfirm() {
    confirm({
      title: "Do you want to delete these items?",
      icon: ExclamationCircleOutlined,
      content:
        "When clicked the OK button, this dialog will be closed after 1 second",
      onOk() {
        return new Promise((resolve, reject) => {
          setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
        }).catch(() => console.log("Oops errors!"));
      },
      onCancel() {}
    });
  }
</script>

Information Modal Dialog

The information modal dialog is used to communicate system status. Only one button is used to close the dialog.

<div class="information-buttons">
  <Button on:click="{info}">Info</Button>
  <Button on:click="{success}">Success</Button>
  <Button on:click="{error}">Error</Button>
  <Button on:click="{warning}">Warning</Button>
</div>

<script>
  import { Button, Modal } from "svant";
  import ModalInfoContent from "./ModalInfoExample.svelte";

  function info() {
    Modal.info({
      title: "This is a notification message",
      content: ModalInfoContent,
      autoFocusButton: "ok",
      onOk() {
        console.log("OK Clicked");
      }
    });
  }

  function success() {
    Modal.success({
      content: "some messages...some messages..."
    });
  }

  function error() {
    Modal.error({
      title: "This is an error message",
      content: "some messages...some messages..."
    });
  }

  function warning() {
    Modal.warning({
      title: "This is a warning message",
      content: "some messages...some messages...",
      closeable: true
    });
  }
</script>

Manually Updating and Destroying

Use Svelte's built in $set function to update the modal. The Modal.destroy() function will destroy a modal.

<Button on:click="{countDown}">Open modal to close in 3s</Button>

<script>
  import { Button, Modal } from "svant";

  function countDown() {
    let secondsToGo = 3;
    const modal = Modal.success({
      title: "This is a notification message",
      content: `This modal will be destroyed after ${secondsToGo} second.`
    });
    const timer = setInterval(() => {
      secondsToGo -= 1;
      modal.$set({
        content: `This modal will be destroyed after ${secondsToGo} second.`
      });
    }, 1000);
    setTimeout(() => {
      clearInterval(timer);
      modal.destroy();
    }, secondsToGo * 1000);
  }
</script>

Positioning

You can use the centered prop, or set the verticalPosition's top or bottom to position the modal.

<Button type="primary" on:click="{() => setModal1Visible(true)}">
  Open 20px from the top
</Button>

<Button type="primary" on:click="{() => setModal2Visible(true)}">
  Vertically centered
</Button>

<Modal
  title="Top right corner"
  verticalPosition="{{ top: '20px' }}"
  visible="{modal1Visible}"
  on:ok="{() => setModal1Visible(false)}"
  on:cancel="{() => setModal1Visible(false)}">
  <p>some contents...</p>
  <p>some contents...</p>
  <p>some contents...</p>
</Modal>

<Modal
  title="Vertically centered modal dialog"
  centered
  visible="{modal2Visible}"
  on:ok="{() => setModal2Visible(false)}"
  on:cancel="{() => setModal2Visible(false)}">
  <p>some contents...</p>
  <p>some contents...</p>
  <p>some contents...</p>
</Modal>

<script>
  import { Button, Modal } from "svant";

  export let modal1Visible = false;
  export let modal2Visible = false;

  function setModal1Visible(visible) {
    modal1Visible = visible;
  }

  function setModal2Visible(visible) {
    modal2Visible = visible;
  }
</script>

Destroying all Modals Open

Modal.destroyAll() will destroy all confirmation modal dialogs.

<Button on:click="{showAll}">Show Modal</Button>

<script>
  import { Button, Modal } from "svant";
  import { ExclamationCircleOutlined } from "svant/icons";

  const { confirm } = Modal;

  function showAll() {
    for (let i = 0; i < 3; i += 1) {
      setTimeout(() => {
        confirm({
          icon: ExclamationCircleOutlined,
          content: "Clicking any button will close all three",
          onOk() {
            destroyAll();
          },
          onCancel() {
            destroyAll();
          }
        });
      }, i * 500);
    }
  }

  function destroyAll() {
    Modal.destroyAll();
  }
</script>

API

Attributes

PropertyDescriptionTypeDefault
bodyStyleBody style for modal body element. Such as height, padding etc.String|Object
cancelTextText of the Cancel button.StringCancel
centeredCentered ModalBooleanfalse
closableWhether a close (x) button is visible on top right of the modal dialog or not.Booleantrue
closeIconCustom close icon.SvelteComponentCloseOutlined
confirmLoadingWhether to apply loading visual effect for OK button or not.Booleanfalse
maskWhether show mask or not.Booleantrue
maskClosableWhether to close the modal dialog when the mask (area outside the modal) is clicked.Booleantrue
maskStyleStyle for modal's mask element.String|Object
okTextText of the OK button.StringOK
okTypeButton `type` of the OK button.Stringprimary
okButtonPropsThe OK button props.Object{}
cancelButtonPropsThe Cancel button props.Object{}
verticalPositionThe vertical position of the modal (top or bottom)Object{}
titleThe modal dialog's titleString-
visibleWhether the modal dialog is visible or not.Booleanfalse
widthWidth of the modal dialog.String520px
wrapClassNameThe class name of the container of the modal dialog.String-
zIndexThe `z-index` of the Modal.Number1000
autoFocusButtonSpecify which button to autofocus when the modal opens.null|'ok'|'cancel'ok
keyboardWhether the escape key will close the modal.Booleantrue

Events

NameDescription
cancelSpecify a function that will be called when a user clicks mask, close button on top right or Cancel button.
okSpecify a function that will be called when a user clicks the OK button.
undefinedSpecify a function that will be called when modal is closed completely.

Modal.method()

There are five ways to display the information based on the content's nature:

  • Modal.info
  • Modal.success
  • Modal.error
  • Modal.warning
  • Modal.confirm

The items listed above are all functions, expecting a settings object as parameter. The settings object takes any of the props above as attributes.

Note: The closeable and maskClosable props default to false for these types of modals.

Additionally these options are available:

Modal.method() Attributes

PropertyDescriptionTypeDefault
contentContent for the modal body.String|SvelteComponent-
iconCustom icon to display next to the content.SvelteComponentDepends on the modal method
onCancelSpecify a function that will be called when a user clicks mask, close button on top right or Cancel button.Function-
onOkSpecify a function that will be called when a user clicks the OK button.Function-