Usage Guide
svelte-french-toast
provides a flexible API for creating various types of toasts. This guide covers the most common use cases.
Toast Types
The library offers several built-in toast types for different scenarios.
Success
Use toast.success()
to indicate that an operation was successful.
toast.success('Successfully toasted!');
Error
Use toast.error()
for failed operations or to display error messages.
toast.error("This didn't work.");
Default (Blank)
For a neutral toast without a default icon, call the toast()
function directly.
toast('Here is your toast.');
Promise API
This is one of the most powerful features. The toast.promise()
function automatically handles the lifecycle of a Promise, showing different toasts for its loading, success, and error states.
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
resolve('Success!');
} else {
reject('Error!');
}
}, 1000);
});
toast.promise(
myPromise,
{
loading: 'Saving...',
success: 'Settings saved!',
error: 'Could not save.',
}
);
Customization
You can customize each toast by passing an options object as the second argument.
Icons and Emojis
Provide a custom icon or emoji.
toast('Good Job!', {
icon: '👏',
});
Dark Mode & Styling
Apply custom styles directly to a toast using the style
option.
toast('Hello Darkness!', {
icon: '🌚',
style: 'border-radius: 200px; background: #333; color: #fff;'
});
Theming
For more control over the built-in icons, use the iconTheme
option.
toast.success('Look at me!', {
style: 'border: 1px solid #713200; padding: 16px; color: #713200;',
iconTheme: {
primary: '#713200',
secondary: '#FFFAEE'
}
});
Multiline Messages
Toasts can handle multiline strings. Use \n
to create line breaks.
toast(
"This toast is super big. I don't think anyone could eat it in one bite.\n\nIt's larger than you expected. You eat it but it does not seem to get smaller.",
{
duration: 6000,
}
);
Rich Content with Svelte Components
For fully interactive and custom toasts, you can render any Svelte component as the message. This is achieved by using toast.custom()
or passing the component to the default toast()
function.
First, create your custom component.
RichContent.svelte
<script lang="ts">
import toast, { type Toast } from 'svelte-french-toast';
// The toast object is passed down as a prop
export let toast: Toast;
export let someProp: string;
</script>
<span>
Custom and <b>bold</b> with props like {someProp}!
<button on:click={() => toast.dismiss(toast.id)}>Dismiss</button>
</span>
Then, render it in a toast. You can pass props to your component via the props
key in the toast options.
App.svelte
<script>
import toast from 'svelte-french-toast';
import RichContent from './RichContent.svelte';
function showRichToast() {
toast(RichContent, {
props: { someProp: '⭐' }
});
}
</script>
<button on:click={showRichToast}>Show Rich Toast</button>