> ## Documentation Index
> Fetch the complete documentation index at: https://veekthoven-laravel-inertia-toast-24-61.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# React

> Set up Laravel Inertia Toast with React

Learn how to integrate Laravel Inertia Toast with React. This guide covers provider setup, component configuration, and usage of the `useToast` hook.

## Installation

First, install the React package:

```bash theme={null}
npm install @laravel-inertia-toast/react
```

## Setup

<Steps>
  <Step title="Wrap your app with ToastProvider">
    In your main application file (typically `app.jsx` or `app.tsx`), import and wrap your application with the `ToastProvider`:

    ```tsx theme={null}
    import { createRoot } from 'react-dom/client'
    import { createInertiaApp } from '@inertiajs/react'
    import { ToastProvider, Toasts } from '@laravel-inertia-toast/react'

    createInertiaApp({
      resolve: (name) => {
        const pages = import.meta.glob('./Pages/**/*.tsx', { eager: true })
        return pages[`./Pages/${name}.tsx`]
      },
      setup({ el, App, props }) {
        createRoot(el).render(
          <ToastProvider>
            <App {...props} />

    		<Toasts />
          </ToastProvider>
        )
      },
    })
    ```

    <Info>
      The `ToastProvider` automatically listens to Inertia's `flash` event and displays toasts from your Laravel backend.
    </Info>
  </Step>

  <Step title="Configure the provider (optional)">
    You can customize the default behavior by passing a `config` prop:

    ```tsx theme={null}
    <ToastProvider
      config={{
        duration: 5000,
        position: 'top-right',
        maxVisible: 5,
        propKey: 'toasts',
      }}
    >
      <App {...props} />
    </ToastProvider>
    ```

    ### Configuration options

    | Option       | Type     | Default       | Description                                                                                                       |
    | ------------ | -------- | ------------- | ----------------------------------------------------------------------------------------------------------------- |
    | `duration`   | `number` | `5000`        | Default duration in milliseconds before toasts auto-dismiss                                                       |
    | `position`   | `string` | `'top-right'` | Toast position: `'top-right'`, `'top-left'`, `'top-center'`, `'bottom-right'`, `'bottom-left'`, `'bottom-center'` |
    | `maxVisible` | `number` | `5`           | Maximum number of toasts visible at once                                                                          |
    | `propKey`    | `string` | `'toasts'`    | The flash key used in Laravel responses                                                                           |
  </Step>
</Steps>

## Using the hook

The `useToast` hook provides methods to programmatically create toasts from your React components.

### Basic usage

```tsx theme={null}
import { useToast } from '@laravel-inertia-toast/react'

export default function MyComponent() {
  const toast = useToast()

  function handleSuccess() {
    toast.success('Operation completed successfully!')
  }

  function handleError() {
    toast.error('Something went wrong!')
  }

  return (
    <div>
      <button onClick={handleSuccess}>Show Success</button>
      <button onClick={handleError}>Show Error</button>
    </div>
  )
}
```

### Available methods

The `useToast` hook returns an object with the following methods:

#### `success(message, options?)`

Displays a success toast.

```typescript theme={null}
toast.success('Your changes have been saved!')

// With options
toast.success('Profile updated!', {
  title: 'Success',
  duration: 3000,
})
```

#### `error(message, options?)`

Displays an error toast.

```typescript theme={null}
toast.error('Failed to save changes')

// With options
toast.error('Invalid credentials', {
  title: 'Authentication Error',
  duration: 7000,
})
```

#### `info(message, options?)`

Displays an info toast.

```typescript theme={null}
toast.info('New features are available')

// With options
toast.info('Check your email for verification', {
  title: 'Info',
  duration: 4000,
})
```

#### `warning(message, options?)`

Displays a warning toast.

```typescript theme={null}
toast.warning('Your session will expire soon')

// With options
toast.warning('Unsaved changes detected', {
  title: 'Warning',
  duration: 6000,
})
```

### Toast options

You can customize individual toasts using the `options` parameter:

```typescript theme={null}
interface ToastOptions {
  title?: string       // Optional title displayed above the message
  duration?: number    // Custom duration in milliseconds (overrides default)
}
```

## TypeScript support

The package is written in TypeScript and includes full type definitions:

```typescript theme={null}
import type {
  ToastLevel,
  ToastMessage,
  ToastItemType,
  ToastConfig,
  ToastProviderProps,
  ToastContextValue,
  ToastOptions,
} from '@laravel-inertia-toast/react'

// Toast levels
type ToastLevel = 'success' | 'error' | 'info' | 'warning'

// Toast message structure
interface ToastMessage {
  message: string
  level: ToastLevel
  title: string | null
  duration: number | null
}

// Toast item with ID
interface ToastItemType extends ToastMessage {
  id: string
}

// Configuration options
interface ToastConfig {
  duration: number
  position: string
  maxVisible: number
  propKey: string
}

// Provider props
interface ToastProviderProps {
  children: React.ReactNode
  config?: Partial<ToastConfig>
}

// Hook return value
interface ToastContextValue {
  items: ToastItemType[]
  config: ToastConfig
  success: (message: string, options?: ToastOptions) => void
  error: (message: string, options?: ToastOptions) => void
  info: (message: string, options?: ToastOptions) => void
  warning: (message: string, options?: ToastOptions) => void
  remove: (id: string) => void
  clear: () => void
}
```

## Advanced usage

### Custom toast wrapper

You can create a custom wrapper component with predefined settings:

```tsx theme={null}
import { useToast } from '@lombacode/laravel-inertia-toast-react'

export function useNotifications() {
  const toast = useToast()

  return {
    success: (message: string) =>
      toast.success(message, {
        title: 'Success',
        duration: 3000,
      }),
    error: (message: string) =>
      toast.error(message, {
        title: 'Error',
        duration: 7000,
      }),
    notify: (message: string) =>
      toast.info(message, {
        title: 'Notification',
        duration: 5000,
      }),
  }
}

// Usage in components
export default function MyComponent() {
  const notifications = useNotifications()

  return (
    <button onClick={() => notifications.success('Task completed!')}>Complete Task</button>
  )
}
```

### Context access

For advanced use cases, you can access the `ToastContext` directly:

```tsx theme={null}
import { useContext } from 'react'
import { ToastContext } from '@laravel-inertia-toast/react'

export default function AdvancedComponent() {
  const context = useContext(ToastContext)

  if (!context) {
    throw new Error('Must be used within ToastProvider')
  }

  // Use context.items, context.config, etc.
  return <div>Active toasts: {context.items.length}</div>
}
```

<Warning>
  Direct context access is for advanced use cases. It is unnecessary and highly discouraged. Use the `useToast` hook for most scenarios.
</Warning>

## Next steps

<CardGroup cols={2}>
  <Card icon="palette" href="/advanced/customization" title="Styling">
    Customize the appearance of your toasts
  </Card>

  <Card icon="php" href="/usage/server-side" title="Laravel setup">
    Configure Laravel to send toast notifications
  </Card>
</CardGroup>
