Convert Figma logo to code with AI

wobsoriano logosvelte-sonner

An opinionated toast component for Svelte. A port of @emilkowalski's sonner.

1,093
31
1,093
20

Top Related Projects

10,969

An opinionated toast component for React.

Smoking Hot React Notifications 🔥

React notification made easy 🚀 !

Highly customizable notification snackbars (toasts) that can be stacked on top of each other

🍞 A toast notification system for react

Quick Overview

Svelte-sonner is a toast component for Svelte applications, inspired by the popular React library 'sonner'. It provides an easy-to-use, customizable, and accessible way to display toast notifications in Svelte projects.

Pros

  • Simple API and easy integration with Svelte applications
  • Customizable appearance and behavior
  • Accessible, with support for screen readers
  • Lightweight and performant

Cons

  • Limited to Svelte applications only
  • May require additional setup for complex use cases
  • Documentation could be more comprehensive
  • Relatively new project, potentially less stable than more established alternatives

Code Examples

  1. Basic usage:
<script>
  import { toast } from 'svelte-sonner'
</script>

<button on:click={() => toast('My first toast')}>
  Show Toast
</button>
  1. Custom toast with options:
<script>
  import { toast } from 'svelte-sonner'
</script>

<button on:click={() => toast.success('Task completed', {
  description: 'The task was successfully completed.',
  duration: 5000
})}>
  Show Success Toast
</button>
  1. Using the Toaster component:
<script>
  import { Toaster } from 'svelte-sonner'
</script>

<Toaster richColors />

Getting Started

  1. Install the package:
npm install svelte-sonner
  1. Import and use in your Svelte component:
<script>
  import { toast, Toaster } from 'svelte-sonner'
</script>

<Toaster />

<button on:click={() => toast('Hello, World!')}>
  Show Toast
</button>
  1. Customize as needed:
<Toaster position="top-center" expand={true} richColors />

Competitor Comparisons

10,969

An opinionated toast component for React.

Pros of sonner

  • More established project with a larger community and more contributors
  • Supports multiple JavaScript frameworks (React, Vue, Solid)
  • More customizable with additional features like custom icons and animations

Cons of sonner

  • Larger bundle size due to supporting multiple frameworks
  • May have unnecessary code for users only interested in Svelte integration
  • Potentially more complex API due to cross-framework compatibility

Code Comparison

sonner (React example):

import { Toaster, toast } from 'sonner'

function MyComponent() {
  return (
    <div>
      <Toaster />
      <button onClick={() => toast('My first toast')}>
        Give me a toast
      </button>
    </div>
  )
}

svelte-sonner:

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

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

Both libraries offer similar APIs, but svelte-sonner provides a more Svelte-native approach with its component syntax and event handling. sonner requires slightly more setup for React components, while svelte-sonner integrates more seamlessly with Svelte's component structure.

Smoking Hot React Notifications 🔥

Pros of react-hot-toast

  • Larger community and more widespread adoption, leading to better support and resources
  • More comprehensive documentation with interactive examples
  • Supports custom render functions for advanced customization

Cons of react-hot-toast

  • Limited to React applications, while svelte-sonner is specifically designed for Svelte
  • Slightly larger bundle size compared to svelte-sonner
  • Less opinionated styling, which may require more effort to achieve a consistent look

Code Comparison

react-hot-toast:

import { toast } from 'react-hot-toast';

toast('Hello World');
toast.success('Successfully created!');
toast.error('This is an error!');

svelte-sonner:

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

toast('Hello World')
toast.success('Successfully created!')
toast.error('This is an error!')
</script>

<Toaster />

Both libraries offer similar APIs for creating toasts, with slight differences in syntax due to the frameworks they're built for. react-hot-toast doesn't require a separate component for rendering toasts, while svelte-sonner uses the <Toaster /> component to handle toast rendering.

React notification made easy 🚀 !

Pros of react-toastify

  • More mature and widely adopted, with a larger community and ecosystem
  • Offers a wider range of customization options and features
  • Supports multiple toast types (success, error, info, etc.) out of the box

Cons of react-toastify

  • Larger bundle size due to more features and dependencies
  • Steeper learning curve for advanced customizations
  • React-specific, limiting its use in other frameworks

Code Comparison

react-toastify:

import { toast } from 'react-toastify';

toast.success('Success message');
toast.error('Error message');
toast.info('Info message');

svelte-sonner:

import { toast } from 'svelte-sonner';

toast.success('Success message');
toast.error('Error message');
toast('Default message');

Both libraries offer similar basic functionality for displaying toast notifications. react-toastify provides more built-in toast types, while svelte-sonner has a simpler API with fewer options out of the box.

react-toastify is a more comprehensive solution with a wider range of features, making it suitable for complex applications with diverse notification requirements. However, this comes at the cost of a larger bundle size and potentially more complex setup.

svelte-sonner, being Svelte-specific, integrates more seamlessly with Svelte applications and offers a lighter-weight solution. It's ideal for projects that prioritize simplicity and smaller bundle sizes, though it may require more custom work for advanced use cases.

Highly customizable notification snackbars (toasts) that can be stacked on top of each other

Pros of notistack

  • Designed for React applications, offering seamless integration with React components
  • Supports stacking multiple snackbars with customizable positioning
  • Provides a higher-order component for easy integration with material-ui

Cons of notistack

  • Limited to React ecosystem, not suitable for Svelte projects
  • Requires additional setup and configuration compared to svelte-sonner
  • May have a steeper learning curve for developers new to React

Code Comparison

notistack:

import { SnackbarProvider, useSnackbar } from 'notistack';

function MyApp() {
  const { enqueueSnackbar } = useSnackbar();
  return <button onClick={() => enqueueSnackbar('Hello!')}>Show snackbar</button>;
}

svelte-sonner:

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

<button on:click={() => toast('Hello!')}>Show toast</button>

Both libraries offer simple APIs for displaying notifications, but svelte-sonner provides a more concise implementation specific to Svelte applications. notistack requires wrapping the application with a provider component, while svelte-sonner can be used directly without additional setup.

🍞 A toast notification system for react

Pros of react-toast-notifications

  • More mature and established project with a larger user base
  • Offers more customization options for toast appearance and behavior
  • Provides built-in support for accessibility features

Cons of react-toast-notifications

  • Limited animation options compared to svelte-sonner
  • Requires more setup and configuration to get started
  • Less frequent updates and maintenance

Code Comparison

react-toast-notifications:

import { useToasts } from 'react-toast-notifications'

function MyComponent() {
  const { addToast } = useToasts()
  return <button onClick={() => addToast('Hello World', { appearance: 'success' })}>Show Toast</button>
}

svelte-sonner:

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

<button on:click={() => toast.success('Hello World')}>Show Toast</button>

Both libraries offer straightforward ways to create and display toast notifications. react-toast-notifications uses a hook-based approach, while svelte-sonner provides a more direct method for showing toasts. The svelte-sonner syntax is slightly more concise, but both are relatively easy to use.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

https://github.com/wobsoriano/svelte-sonner/assets/13049130/4b9c250f-1431-4130-9c5b-5a4f8b0210c5

svelte-sonner

pnpm

An opinionated toast component for Svelte. A port of Emil Kowalski's Sonner.

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 onclick={() => 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 onclick={() => dispatch('closeToast')}>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

Styling can be done globally via toastOptions, this way every toast will have the same styling.

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

You can also use the same props when calling toast to style a specific toast.

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

Tailwind CSS

The preferred way to style the toasts with tailwind is by using the unstyled prop. That will give you an unstyled toast which you can then style with tailwind.

<Toaster
	toastOptions={{
		unstyled: true,
		classes: {
			toast: 'bg-blue-400',
			title: 'text-red-400',
			description: 'text-red-400',
			actionButton: 'bg-zinc-400',
			cancelButton: 'bg-orange-400',
			closeButton: 'bg-lime-400'
		}
	}}
/>

You can do the same when calling toast().

toast('Hello World', {
	unstyled: true,
	classes: {
		toast: 'bg-blue-400',
		title: 'text-red-400 text-2xl',
		description: 'text-red-400',
		actionButton: 'bg-zinc-400',
		cancelButton: 'bg-orange-400',
		closeButton: 'bg-lime-400'
	}
});

Styling per toast type is also possible.

<Toaster
	toastOptions={{
		unstyled: true,
		classes: {
			error: 'bg-red-400',
			success: 'text-green-400',
			warning: 'text-yellow-400',
			info: 'bg-blue-400'
		}
	}}
/>

Changing Icon

You can change the default icons using snippets:

<Toaster>
	{#snippet loadingIcon()}
		<LoadingIcon />
	{/snippet}
	{#snippet successIcon()}
		<SuccessIcon />
	{/snippet}
	{#snippet errorIcon()}
		<ErrorIcon />
	{/snippet}
	{#snippet infoIcon()}
		<InfoIcon />
	{/snippet}
	{#snippet warningIcon()}
		<WarningIcon />
	{/snippet}
</Toaster>

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). The toast() function returns the id of the toast.

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

toast.dismiss(toastId);

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

toast.dismiss();

useSonner

You can use the useSonner hook to retrieve all visible toasts like below.

const sonner = useSonner();

$effect(() => console.log(sonner.toasts));

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

NPM DownloadsLast 30 Days