sonner.tsx


Overview

The sonner.tsx file defines a React component named Toaster that serves as a styled wrapper around the Toaster component from the sonner notification library. This component integrates theme-awareness using the next-themes package to dynamically adjust its appearance based on the current UI theme (light, dark, or system). It applies custom styling that aligns the toast notifications with the overall design system of the application. The component facilitates displaying toast notifications with consistent theming and customized visual styles.


Detailed Breakdown

Imports


Type Aliases

type ToasterProps = React.ComponentProps<typeof Sonner>;

Component: Toaster

const Toaster = ({ ...props }: ToasterProps) => {
  const { theme = 'system' } = useTheme();

  return (
    <Sonner
      theme={theme as ToasterProps['theme']}
      className="toaster group"
      toastOptions={{
        classNames: {
          toast:
            'group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg',
          description: 'group-[.toast]:text-muted-foreground',
          actionButton:
            'group-[.toast]:bg-primary group-[.toast]:text-primary-foreground',
          cancelButton:
            'group-[.toast]:bg-muted group-[.toast]:text-muted-foreground',
        },
      }}
      {...props}
    />
  );
};

Purpose

Parameters

Return Value

Usage Example

import { Toaster } from './sonner';

// To display toast notifications globally in your app
function App() {
  return (
    <>
      {/* Other app components */}
      <Toaster position="bottom-right" />
    </>
  );
}

Important Implementation Details


Interaction with Other Parts of the System


Mermaid Diagram

This component file contains a single functional component wrapping a third-party component, so a component diagram illustrating the structure and prop flow is appropriate.

componentDiagram
    component Toaster {
        +props: ToasterProps
        +theme: 'light' | 'dark' | 'system'
    }

    component Sonner {
        +theme: string
        +className: string
        +toastOptions: object
        +otherProps: any
    }

    Toaster --> Sonner : wraps and forwards props
    Toaster ..> useTheme : uses current theme

Summary

The sonner.tsx file provides a reusable, theme-aware toast notification component for a React/Next.js application. By encapsulating the third-party Sonner Toaster and integrating it with the app's theme context, it ensures consistent and customizable user feedback notifications that adapt visually based on the app's theme settings. The use of scoped Tailwind CSS classes further enhances styling flexibility while keeping the API simple and extensible. This component is intended to be included once per app to manage toast notifications globally.