Giter VIP home page Giter VIP logo

svelte-sonner's Introduction

SvelteSonnerDemo.mp4

svelte-sonner

pnpm

An opinionated toast component for Svelte.

Based on emilkowalski's React implementation.

Quick start

Install it:

npm i svelte-sonner
# or
yarn add svelte-sonner
# or
pnpm add svelte-sonner

Add <Toaster /> to your app, it will be the place where all your toasts will be rendered. After that, you can use toast() from anywhere in your app.

<script>
import { Toaster, toast } from 'svelte-sonner'
</script>

<Toaster />
<button on:click={() => toast('My first toast')}>Give me a toast</button>

Types

Default

Most basic toast. You can customize it (and any other type) by passing an options object as the second argument.

toast('Event has been created')

With custom icon and description:

import Icon from './Icon.svelte'

toast('Event has been created', {
  description: 'Monday, January 3rd at 6:00pm',
  icon: Icon,
})

Success

Renders a checkmark icon in front of the message.

toast.success('Event has been created')

Error

Renders an error icon in front of the message.

toast.error('Event has not been created')

Action

Renders a button.

toast('Event has been created', {
  action: {
    label: 'Undo',
    onClick: () => console.log('Undo'),
  },
})

Promise

Starts in a loading state and will update automatically after the promise resolves or fails.

toast.promise(() => new Promise(resolve => setTimeout(resolve, 2000)), {
  loading: 'Loading',
  success: 'Success',
  error: 'Error',
})

You can pass a function to the success/error messages to incorporate the result/error of the promise.

toast.promise(promise, {
  loading: 'Loading...',
  success: (data) => {
    return `${data.name} has been added!`
  },
  error: 'Error',
})

Custom Component

You can pass a component as the first argument instead of a string to render custom component while maintaining default styling. You can use the headless version below for a custom, unstyled toast.

toast(CustomComponent)

Updating a toast

You can update a toast by using the toast function and passing it the id of the toast you want to update, the rest stays the same.

const toastId = toast('Sonner')

toast.success('Toast has been updated', {
  id: toastId,
})

Customization

Headless

You can use toast.custom to render an unstyled toast with custom component while maintaining the functionality.

<script>
import { createEventDispatcher } from 'svelte';

const dispatch = createEventDispatcher()
</script>

 <div>
  This is a custom component <button on:click={() => dispatch('removeToast')}>close</button>
</div>
import HeadlessToast from './HeadlessToast.svelte'

toast.custom(HeadlessToast)

Theme

You can change the theme using the theme prop. Default theme is light.

<Toaster theme="dark" />

Position

You can change the position through the position prop on the <Toaster /> component. Default is bottom-right.

<!-- Available positions -->
<!-- top-left, top-center, top-right, bottom-left, bottom-center, bottom-right -->

<Toaster position="top-center" />

Expanded

Toasts can also be expanded by default through the expand prop. You can also change the amount of visible toasts which is 3 by default.

<Toaster expand visibleToasts={9} />

Styling for all toasts

You can style your toasts globally with the toastOptions prop in the Toaster component.

<Toaster
  toastOptions={{ style: 'background: red;', class: 'my-toast', descriptionClass: 'my-toast-description' }}
/>

Styling for individual toast

toast('Event has been created', {
  style: 'background: red;',
  class: 'my-toast',
  descriptionClass: 'my-toast-description',
})

Close button

Add a close button to all toasts that shows on hover by adding the closeButton prop.

<Toaster closeButton />

Rich colors

You can make error and success state more colorful by adding the richColors prop.

<Toaster richColors />

Custom offset

Offset from the edges of the screen.

<Toaster offset="80px" />

Programmatically remove toast

To remove a toast programmatically use toast.dismiss(id).

const toastId = toast('Event has been created')

toast.dismiss(toastId)

To remove a toast from inside a custom component, dispatch closeToast:

import { createEventDispatcher } from 'svelte'

const dispatch = createEventDispatcher()

dispatch('removeToast')

You can also use the dismiss method without the id to dismiss all toasts.

// Removes all toasts

toast.dismiss()

Duration

You can change the duration of each toast by using the duration property, or change the duration of all toasts like this:

<Toaster duration={10000} />
toast('Event has been created', {
  duration: 10000,
})

// Persisent toast
toast('Event has been created', {
  duration: Number.POSITIVE_INFINITY,
})

On Close Callback

You can pass onDismiss and onAutoClose callbacks. onDismiss gets fired when either the close button gets clicked or the toast is swiped. onAutoClose fires when the toast disappears automatically after it's timeout (duration prop).

toast('Event has been created', {
  onDismiss: t => console.log(`Toast with id ${t.id} has been dismissed`),
  onAutoClose: t => console.log(`Toast with id ${t.id} has been closed automatically`),
})

Keyboard focus

You can focus on the toast area by pressing โŒฅ/alt + T. You can override it by providing an array of event.code values for each key.

<Toaster hotkey={['KeyC']} />

License

MIT

svelte-sonner's People

Contributors

wobsoriano avatar fabiot21 avatar thaunknown avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.