• Stars
    star
    637
  • Rank 70,628 (Top 2 %)
  • Language Svelte
  • License
    MIT License
  • Created over 1 year ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An opinionated toast component for Svelte. A port of @emilkowalski's sonner.
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');

Info

Renders a question mark icon in front of the message.

toast.info('Event has new information');

Warning

Renders a warning icon in front of the message.

toast.warning('Event has warning');

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('closeToast');

You can also dismiss all toasts at once by calling toast.dismiss() without an id.

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

More Repositories

1

v-dashboard

Dashboard starter template built with Vue 3 and Tailwind CSS.
Vue
788
star
2

trpc-nuxt

End-to-end typesafe APIs in Nuxt applications.
TypeScript
672
star
3

covid3d

🌏 An interactive 3D visualization of COVID-19.
JavaScript
280
star
4

lexical-vue

An extensible Vue 3 web text-editor based on Lexical.
TypeScript
214
star
5

numix

Write your server code inside Vue SFC's and handle forms easily.
TypeScript
214
star
6

vite-react-tailwind-starter

Starter using Vite + React + Tailwind CSS 2
TypeScript
200
star
7

vue-motion-one

Animation library for Vue 3 based on Motion One.
TypeScript
154
star
8

h3-zod

TypeScript-first schema validation for h3 and Nuxt applications
TypeScript
150
star
9

poke95

🚀 A Windows 95 style Pokédex built with React.
JavaScript
148
star
10

v-perfect-signature

Pressure-sensitive signature drawing for Vue 2 and 3
TypeScript
147
star
11

2019-ncov-frontend

🌏 Map, data and timeline of coronavirus (COVID-19)
Vue
147
star
12

blipgloss

Style definitions for nice terminal layouts 👄
TypeScript
145
star
13

codeplayground

Codepen.io clone using Vue 3 and Monaco Editor
Vue
136
star
14

rn-perfect-sketch-canvas

Perfect pressure-sensitive drawing for both iOS and Android.
TypeScript
127
star
15

vue-clerk

Community Vue SDK for Clerk.
TypeScript
126
star
16

pinia-shared-state

🍍 Sync your Pinia state across browser tabs.
TypeScript
123
star
17

bnx

zx inspired shell for Bun.
TypeScript
123
star
18

onlysetups

OnlyFans, but for pictures of desk setups.
JavaScript
115
star
19

vue-winbox

A wrapper component for WinBox.js with the ability to mount Vue components.
Vue
114
star
20

vue-wrap-balancer

Simple Vue Component That Makes Titles More Readable.
Vue
110
star
21

elysia-autoroutes

File system routes for Elysia.js.
TypeScript
107
star
22

vuetify-sonner

Stackable toast component for Vuetify.
Vue
104
star
23

vagmi

Vue composables for Ethereum
TypeScript
103
star
24

bun-promptx

Terminal prompt library for the Bun runtime
Go
92
star
25

nuxt-remote-fn

Remote Functions. Instead of Event Handlers.
TypeScript
92
star
26

vue-cart

Shopping cart example using Vue 3 and Pinia
Vue
90
star
27

vue-keep

Google Keep clone with Vue, Typescript and Firestore
Vue
89
star
28

nuxt-proxy

Http-proxy middleware for Nuxt 3.
TypeScript
88
star
29

siopao

A minimal routing library designed to sit on top of Bun's fast HTTP server.
TypeScript
85
star
30

spotify-stats

🎧 Your spotify profile's top artists and tracks with charts and playlist creator.
JavaScript
83
star
31

coderstats

📊 Data visualizations of your top languages, starred repositories and top repos.
Svelte
82
star
32

nuxt-clerk-template

Auth starts here with the Nuxt and Clerk Demo
Vue
81
star
33

bun-plugin-dts

A Bun plugin for generating dts files.
TypeScript
77
star
34

solid-zustand

🐻 State management in Solid using zustand.
TypeScript
76
star
35

bun-lib-starter

My minimal bun library starter
TypeScript
73
star
36

solid-firebase

Solid primitives for Firebase v9.
TypeScript
73
star
37

coronavirus-ph-api

🦠 An API for tracking the coronavirus (COVID-19, SARS-CoV-2) outbreak in the Philippines.
JavaScript
70
star
38

solid-sonner

An opinionated toast component for Solid.
TypeScript
69
star
39

bunbot

Desktop automation for Bun
Go
64
star
40

vuemoji-picker

Vue 2 and 3 lightweight emoji picker.
TypeScript
61
star
41

elysia-clerk

Unofficial Clerk plugin for Elysia.js.
TypeScript
60
star
42

h3-formidable

File upload parsing utility for h3 and Nuxt.
TypeScript
59
star
43

nuxt3-socket.io

Nuxt 3 and Socket.io integration.
TypeScript
57
star
44

nuxt-firebase-auth-starter

Authenticated server-side rendering with Nuxt 3 and Firebase 9
TypeScript
54
star
45

2019-ncov-api

Map, data and timeline of coronavirus (COVID-19)
JavaScript
54
star
46

vitest-canvas-mock

🌗 A module used to mock canvas in Vitest.
TypeScript
53
star
47

solid-apexcharts

Solid component for ApexCharts
TypeScript
53
star
48

nuxt3-supabase

Nuxt 3 module and composables for Supabase.
TypeScript
51
star
49

vuetify-use-dialog

Simple confirmation dialog and snackbar composable built on top of Vuetify
Vue
49
star
50

fastify-next-auth

Auth.js plugin for Fastify.
TypeScript
49
star
51

vue-sfc-unbuild

Quickly generate redistributable Vue components with Unbuild.
Vue
48
star
52

authey

Universal support for Auth.js.
TypeScript
46
star
53

vue-input-otp

One time passcode Input. Accessible & unstyled.
Vue
43
star
54

vue-zorm

Type-safe <form> for Vue using Zod
TypeScript
39
star
55

pinia-xstate

Put your xstate state machines into a global pinia store.
TypeScript
39
star
56

svelte-gesture

👇 Bread n butter utility for component-tied mouse/touch gestures in Svelte.
TypeScript
37
star
57

vue-lite-youtube-embed

A private by default, faster and cleaner YouTube embed component for Vue applications.
TypeScript
36
star
58

v-satori

Generate a satori-friendly VDOM from a Vue component
TypeScript
36
star
59

h3-clerk

Unofficial Clerk middleware for H3.
TypeScript
36
star
60

pinia-undo

🍍 Undo/Redo plugin for pinia.
TypeScript
34
star
61

vue-zustand

🐻 Bear necessities for Vue.
TypeScript
32
star
62

svelte-monetization

A minimal and lightweight wrapper for the Web Monetization API
Svelte
32
star
63

vue-cli-plugin-pinia

Vue Cli Pinia plugin
JavaScript
32
star
64

vite-solid-tailwind-starter

Starter using Vite + Solid + Tailwind CSS
TypeScript
31
star
65

solid-jotai

Primitive and flexible state management for Solid based on Jotai.
TypeScript
28
star
66

solid-ninja-keys

Add cmd+k interface to your solid site
TypeScript
26
star
67

deno-systray

A cross-platform systray library for Deno.
TypeScript
26
star
68

solid-supabase

A simple wrapper around Supabase.js to enable usage within Solid.
TypeScript
25
star
69

bun-lightningcss

Lightning CSS plugin for Bun with class composition support.
TypeScript
25
star
70

nuxt-next-auth

Experimental authentication module for Nuxt 2 using NextAuth.
JavaScript
23
star
71

sveltio

Proxy-state with valtio.
TypeScript
23
star
72

solid-whiteboard

TypeScript
22
star
73

nuxt-iron-session

Stateless session support for Nuxt apps
TypeScript
22
star
74

election2020

Simple viz of 2020 presidential election.
JavaScript
22
star
75

solid-stripe

Solid components for Stripe.js and Stripe Elements.
TypeScript
21
star
76

vue-use-places-autocomplete

📍 Vue composable for Google Maps Places Autocomplete.
TypeScript
19
star
77

vue-driver

Drive the user's focus across the page.
TypeScript
18
star
78

vue-markdoc

Vue renderer for Markdoc
TypeScript
17
star
79

h3-session

Session middleware for h3 and Nuxt apps.
TypeScript
17
star
80

solid-gesture

👇 Bread n butter utility for component-tied mouse/touch gestures in Solid.
TypeScript
16
star
81

bun-wifi-name

Get current wifi name in Bun/Node
TypeScript
15
star
82

ffmpeg.wasm-video-to-gif

Vue + FFMPEG.WASM Video to GIF converter
Vue
15
star
83

unplugin-markdoc

Markdoc plugin for Vite/Webpack.
TypeScript
15
star
84

vue-rtk-query

a basic demo on how someone could use rtk-query with Vue 3.
TypeScript
15
star
85

bun-plugin-csv

A Bun plugin which converts .csv and .tsv files into JavaScript modules.
TypeScript
14
star
86

library-starter

My minimal TypeScript library starter
TypeScript
14
star
87

vue3-swatches

🎨 Vue 3 swatch picker
Vue
13
star
88

vite-plugin-markdoc-vue

Render Markdoc extended markdowns as Vue components.
TypeScript
12
star
89

paytrackr

Track and manage your micropayments into one place 🎉
Vue
11
star
90

signl

Signals proposal, but using Vue API!
TypeScript
11
star
91

svelte-clerk

Community package that integrates Clerk with SvelteKit.
Svelte
10
star
92

vue-tailwind-image-gallery

Pixabay image gallery
Vue
10
star
93

v-command-palette

A cmd+k component for Vuetify
Vue
9
star
94

vue-parcel

A simple Vue + Parcel setup for quick prototyping
JavaScript
8
star
95

go-mac-notifier

Send desktop notifications to OSX 10.9 or higher.
Go
8
star
96

rustybun

Readline implementation in Rust for Bun.
Rust
8
star
97

bun-plugin-thumbhash

ThumbHash plugin for Bun
TypeScript
7
star
98

nuxt-web3.js

Nuxt 3 module for Web3.js
TypeScript
7
star
99

cryptostats

📈Top crypto assets by market capitalization.
JavaScript
7
star
100

nuxt-subsystem-demo

TypeScript
7
star