### Install Sonner Source: https://sonner.emilkowal.ski/getting-started Install the Sonner component using pnpm. This is the first step to integrate Sonner into your project. ```bash pnpm i sonner ``` -------------------------------- ### Install Sonner Toast Component Source: https://sonner.emilkowal.ski/ Install the Sonner component using npm. This is the first step to using the toast notifications in your React application. ```bash npm install sonner ``` -------------------------------- ### Render a Basic Toast Source: https://sonner.emilkowal.ski/getting-started Trigger a simple toast message by calling the toast function with your desired message. This example shows how to render a toast when a button is clicked. ```typescript import { toast } from 'sonner'; function MyToast() { return ; } ``` -------------------------------- ### Get All Active Toasts Outside React Source: https://sonner.emilkowal.ski/other Retrieve an array of all currently active toasts outside of a React component context using the `toast.getActiveToasts()` method. ```javascript const toasts = toast.getActiveToasts(); ``` -------------------------------- ### Dynamic Theming with Next-Themes Source: https://sonner.emilkowal.ski/toaster Integrate with a theme provider like `next-themes` to make the toaster's theme adapt dynamically to the app's current theme. ```javascript 'use client'; import { Toaster as SonnerToaster, type ToasterProps } from 'sonner'; import { useTheme } from 'next-themes'; export function Toaster() { const { resolvedTheme } = useTheme(); return ; } ``` -------------------------------- ### Remove All Styles and Apply Custom Classes Source: https://sonner.emilkowal.ski/styling Set the `unstyled` prop to `true` to remove all default Sonner styles and then apply your own classes using `classNames`. This offers maximum control over the toast's appearance. ```javascript toast('Hello World', { unstyled: true, classNames: { toast: 'toast', title: 'title', description: 'description', actionButton: 'action-button', cancelButton: 'cancel-button', closeButton: 'close-button', }, }); ``` -------------------------------- ### Render Toast with Options Source: https://sonner.emilkowal.ski/toast Provide an object as the second argument to the toast function to override default options. This allows for more granular control over toast behavior and appearance. ```javascript toast('Enrollment has closed.', { description: 'This is a longer description', duration: 5000, closeButton: true, position: 'top-right', dismissible: false, icon: '🚀', action: { label: 'Action', onClick: () => console.log('Action clicked!') }, cancel: { label: 'Cancel', onClick: () => console.log('Cancel clicked!') }, id: 'my-toast-id', testId: 'my-toast-test-id', toasterId: 'my-toaster-id', onDismiss: () => console.log('Toast dismissed'), onAutoClose: () => console.log('Toast auto-closed'), containerAriaLabel: 'My custom container', actionButtonStyle: { backgroundColor: 'blue' }, cancelButtonStyle: { backgroundColor: 'red' } }); ``` -------------------------------- ### Render Loading Toast Source: https://sonner.emilkowal.ski/toast Display a toast with a loading spinner. This is useful for manual state management when not using promise-based toasts. ```javascript toast.loading('Processing request...') ``` -------------------------------- ### Render Success Toast Source: https://sonner.emilkowal.ski/toast Display a success toast, which includes a checkmark icon by default. This is useful for confirming successful operations. ```javascript toast.success('Operation successful!') ``` -------------------------------- ### Displaying a Default Toast Source: https://sonner.emilkowal.ski/ Use the `toast()` function to display a default toast message. This is the simplest way to trigger a notification. ```javascript toast('Event has been created') ``` -------------------------------- ### Render Basic Toast Source: https://sonner.emilkowal.ski/toast Call the toast function with a string to display a basic toast message. This string will be used as the toast's title. ```javascript toast('Enrollment has closed.') ``` -------------------------------- ### Apply Global Styles with toastOptions Source: https://sonner.emilkowal.ski/styling Use the `toastOptions` prop on the `Toaster` component to apply consistent styling to all toasts. This is useful for minor adjustments like changing the background color. ```jsx ``` -------------------------------- ### Import Sonner Styles for Astro Source: https://sonner.emilkowal.ski/other Ensure Sonner's styles are correctly loaded in Astro projects, especially those using view transitions, by importing the CSS file into a layout. ```javascript import 'sonner/dist/styles.css'; ``` -------------------------------- ### Render Toast with Action Button Source: https://sonner.emilkowal.ski/toast Add a primary action button to a toast. Clicking this button closes the toast and executes a provided callback. The default behavior can be overridden by preventing event default in the callback. ```javascript toast('My action toast', { action: { label: 'Action', onClick: (event) => { console.log('Action clicked!'); // event.preventDefault(); // Uncomment to prevent toast from closing } } }); ``` ```javascript toast('My action toast', { action: , }); ``` -------------------------------- ### Render Custom Elements in Toasts Source: https://sonner.emilkowal.ski/other Display custom HTML elements, such as links or buttons, within toast titles and descriptions by passing functions that return JSX. ```javascript toast( () => ( <> View an Animation on the Web ), { description: () => , } ); ``` -------------------------------- ### Render Custom Toast with JSX Source: https://sonner.emilkowal.ski/toast Pass JSX as the first argument to the toast function to render a custom toast. This maintains default styling while allowing for custom content. ```javascript toast() ``` -------------------------------- ### Basic Sonner Usage Source: https://sonner.emilkowal.ski/ Render the Toaster component at the root of your application and use the toast function to display notifications. Ensure the Toaster is rendered before attempting to show toasts. ```jsx import { Toaster, toast } from 'sonner' // ... function App() { return (
) } ``` -------------------------------- ### Multiple Toasters with Specific Targeting Source: https://sonner.emilkowal.ski/toaster Render multiple toasters for clear separation and direct toast targeting using the `toasterId` option. ```javascript ``` -------------------------------- ### Expand Toasts on Hover Source: https://sonner.emilkowal.ski/toaster Configure toasts to expand on hover by default. You can also set the maximum number of visible toasts. ```javascript // 9 toasts will be visible instead of the default, which is 3. ``` -------------------------------- ### Render Toast with Cancel Button Source: https://sonner.emilkowal.ski/toast Add a secondary cancel button to a toast. Clicking this button closes the toast and executes a provided callback. ```javascript toast('My cancel toast', { cancel: { label: 'Cancel', onClick: () => console.log('Cancel clicked!') } }); ``` ```javascript toast('My cancel toast', { cancel: , }); ``` -------------------------------- ### Render Promise Toast Source: https://sonner.emilkowal.ski/toast Handle asynchronous operations by displaying a toast that updates based on promise resolution or rejection. Success and error messages can be customized using functions that receive the promise result. ```javascript toast.promise( fetch('/api/data'), { loading: 'Loading data...', success: (data) => `Data loaded successfully: ${JSON.stringify(data)}`, error: (error) => `Failed to load data: ${error.message}` } ); ``` ```javascript toast.promise( async () => { const response = await fetch('/api/data'); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }, { loading: 'Fetching data...', success: (result) => ({ title: 'Success!', description: `Data received: ${JSON.stringify(result)}` }), error: (error) => ({ title: 'Error', description: `Failed to fetch: ${error.message}` }) } ); ``` -------------------------------- ### Toast Dismissal Callbacks Source: https://sonner.emilkowal.ski/other Implement `onDismiss` for manual or swipe dismissals and `onAutoClose` for toasts that disappear after their timeout. ```javascript 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`), }); ``` -------------------------------- ### Style a Specific Toast Source: https://sonner.emilkowal.ski/styling Apply styling to an individual toast by passing style options directly when calling the `toast()` function. This allows for unique styling of particular notifications. ```javascript toast('Hello World', { style: { background: 'red', }, }); ``` -------------------------------- ### Persist Toast Indefinitely Source: https://sonner.emilkowal.ski/other Set a toast to remain on screen permanently by configuring its `duration` property to `Infinity`. ```javascript toast('This toast will stay on screen forever', { duration: Infinity, }); ``` -------------------------------- ### Controlling Toast Expansion Source: https://sonner.emilkowal.ski/ Manage the number of visible toasts using the `visibleToasts` prop on the `Toaster` component. Setting `expand` to `false` disables the expansion behavior. ```jsx ``` -------------------------------- ### Customizing Toaster Offsets Source: https://sonner.emilkowal.ski/toaster Adjust the spacing of toasts from the screen edges using `offset` and `mobileOffset` props. `mobileOffset` applies to screens smaller than 600px. ```javascript // all sides will have 16px offset // all sides will have 10vh offset // 24px from the bottom, 16px from the right and left // mobile offset will be 16px from the bottom, default values for the rest ``` -------------------------------- ### Render Headless Toast with Custom JSX Source: https://sonner.emilkowal.ski/toast Use the headless toast function to render an unstyled toast with custom JSX. This provides access to toast properties via an argument, allowing full control over presentation. ```javascript toast.headless( ({ close, dismiss, ...props }) => (
Custom unstyled toast content
) ); ``` -------------------------------- ### Using Rich Colors for Toasts Source: https://sonner.emilkowal.ski/ Enable rich colors for toasts by adding the `richColors` prop to the `Toaster` component. This applies distinct color schemes to different toast types. ```jsx toast.success('Event has been created') // ... ``` -------------------------------- ### Integrate Toaster into Root Layout Source: https://sonner.emilkowal.ski/getting-started Place the Toaster component in your root layout file (e.g., layout.tsx) to make toasts available throughout your application. This component can be used in server components. ```typescript import { Toaster } from 'sonner'; export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( {children} ); } ``` -------------------------------- ### Manually Add Sonner Styles to Shadow DOM Source: https://sonner.emilkowal.ski/other Adapt Sonner's styling for Shadow DOM environments by manually appending style elements from the document head that contain Sonner's specific selectors. ```javascript document.head.querySelectorAll('style').forEach((styleEl) => { if (styleEl.textContent?.includes('[data-sonner-toaster]')) { shadow.append(styleEl); } }); ``` -------------------------------- ### Render Error Toast Source: https://sonner.emilkowal.ski/toast Display an error toast, which includes an error icon by default. This is suitable for indicating failures or problems. ```javascript toast.error('An error occurred!') ``` -------------------------------- ### Apply Custom Classes Globally Source: https://sonner.emilkowal.ski/styling Use the `classNames` property within `toastOptions` to assign custom CSS classes to different parts of the toast component. This provides a way to integrate with existing CSS frameworks or custom stylesheets. ```jsx ``` -------------------------------- ### Configuring Toaster Position Source: https://sonner.emilkowal.ski/ Customize the position of all toasts by passing the `position` prop to the `Toaster` component. The swipe direction of toasts will adapt to the chosen position. ```jsx ``` -------------------------------- ### Change Toaster Position Source: https://sonner.emilkowal.ski/toaster Customize the rendering position of all toasts. Available positions include top-left, top-center, top-right, bottom-left, bottom-center, and bottom-right. ```javascript // Available positions: // top-left, top-center, top-right, bottom-left, bottom-center, bottom-right ``` -------------------------------- ### Change Default Icons Globally Source: https://sonner.emilkowal.ski/styling Customize the default icons for each toast type (success, info, warning, error, loading) by providing custom React elements to the `icons` prop on the `Toaster` component. ```jsx , info: , warning: , error: , loading: , }} /> ``` -------------------------------- ### Dismiss All Toasts Programmatically Source: https://sonner.emilkowal.ski/other Remove all currently displayed toasts simultaneously by calling `toast.dismiss()` without any arguments. ```javascript toast.dismiss(); ``` -------------------------------- ### Set a Specific Icon for a Toast Source: https://sonner.emilkowal.ski/styling Override the default icon for a single toast by passing a custom icon element to the `icon` prop when calling the `toast()` function. ```javascript toast('Hello World', { icon: , }); ``` -------------------------------- ### Access Active Toasts with useSonner Hook Source: https://sonner.emilkowal.ski/other Retrieve all currently visible toasts within a React component using the `useSonner` hook to manage or interact with them. ```javascript const { toasts } = useSonner(); const toastsAmount = toasts.length; ``` -------------------------------- ### Dismiss All Toasts Using useSonner Source: https://sonner.emilkowal.ski/other Programmatically dismiss all active toasts from within a React component by iterating over the toasts obtained via the `useSonner` hook. ```javascript function removeAllToasts() { toasts.forEach((t) => toast.dismiss(t.id)); } ``` -------------------------------- ### Apply Custom Classes with Tailwind CSS Source: https://sonner.emilkowal.ski/styling When using Tailwind CSS, apply custom classes to toast elements by prefixing them with `!important` to ensure they override default Sonner styles. This allows for seamless integration with Tailwind's utility classes. ```jsx ``` -------------------------------- ### Update Toast Title Source: https://sonner.emilkowal.ski/other Update the title of an existing toast by providing its ID. Other properties remain unchanged. ```javascript const toastId = toast('Sonner'); /** Only title gets updated, the rest stays the same */ tost('Toast has been updated', { id: toastId, }); ``` -------------------------------- ### Update Toast Type Source: https://sonner.emilkowal.ski/other Change the type of an existing toast (e.g., to success or error) using its ID. ```javascript toast.success('Toast has been updated', { id: toastId, }); ``` -------------------------------- ### Dismiss Specific Toast Programmatically Source: https://sonner.emilkowal.ski/other Remove a specific toast using its ID. The `toast()` function returns the ID of the created toast. ```javascript const toastId = toast('Event has been created'); tost.dismiss(toastId); ``` -------------------------------- ### Remove Icon for a Specific Toast Type Source: https://sonner.emilkowal.ski/styling Remove the icon for a particular toast type, such as success toasts, by setting the corresponding icon in the `icons` prop of the `Toaster` component to `null`. ```javascript // Removing the icon for a specific success toast ttoast.success('Hello World', { icon: null, }); // Removing the icon for all success toasts ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.