### Run Development Server Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md Starts the development server, which includes an interactive demo and a harness for testing components. ```bash pnpm start ``` -------------------------------- ### Install React-Toastify Source: https://github.com/fkhadra/react-toastify/blob/main/README.md Install react-toastify using npm or yarn. ```bash $ npm install --save react-toastify $ yarn add react-toastify ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/fkhadra/react-toastify/blob/main/CONTRIBUTING.md Install project dependencies using pnpm. This project uses a pnpm workspace setup. ```bash pnpm install ``` -------------------------------- ### CI Build and Test Workflow Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md The CI workflow in `.github/workflows/build.yaml` automates the build and test process. It installs dependencies, builds the project, runs tests using Cypress, and reports coverage to Coveralls. Coverage instrumentation is handled by `vite-plugin-istanbul`. ```yaml name: Build and Test on: [push, pull_request] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: pnpm/action-setup@v2 with: version: 7 - name: Use Node.js uses: actions/setup-node@v3 with: node-version: 18 - name: Install dependencies run: pnpm install - name: Build run: pnpm build - name: Test run: pnpm test:run - name: Upload artifacts if: failure() uses: actions/upload-artifact@v3 with: name: cypress-screenshots-videos path: cypress/screenshots retention-days: 7 - name: Report coverage if: success() uses: coverallsapp/github-action@v2 with: github-token: ${{ secrets.GITHUB_TOKEN }} path-to-lcov: ./coverage/lcov.info ``` -------------------------------- ### Injecting Stylesheet with Nonce Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md Example of how the `ToastContainer` injects CSS using `useStyleSheet` and accepts a `nonce` prop for CSP compliance. ```typescript useStyleSheet(css, props.nonce) ``` -------------------------------- ### Build the Library Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md Compiles the library using tsup and copies the necessary CSS file to the dist directory. ```bash pnpm build ``` -------------------------------- ### Development Commands for react-toastify Source: https://github.com/fkhadra/react-toastify/blob/main/CONTRIBUTING.md Commands to launch the playground, run tests, and format code using prettier. ```bash # launch the playground pnpm start # Run tests 💩 pnpm test # Prettify all the things pnpm prettier ``` -------------------------------- ### Unstyled Entry Point Source: https://context7.com/fkhadra/react-toastify/llms.txt Use the unstyled entry point to provide your own CSS or import the stylesheet separately. This is useful for custom styling or integrating with build processes. ```tsx // Import unstyled container (no CSS injection) import { ToastContainer, toast } from 'react-toastify/unstyled'; // Import CSS separately in your build import 'react-toastify/dist/ReactToastify.css'; // Or import in CSS: @import 'react-toastify/dist/ReactToastify.css'; function App() { return ( <> ); } ``` -------------------------------- ### Clone Repository and Create Branch Source: https://github.com/fkhadra/react-toastify/blob/main/CONTRIBUTING.md Clone the react-toastify repository and create a new local branch for your contributions. ```bash git clone https://github.com/fkhadra/react-toastify.git cd react-toastify git checkout -b my-branch ``` -------------------------------- ### Open Cypress Component Test UI Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md Launches the Cypress interactive test runner for component testing. ```bash pnpm test ``` -------------------------------- ### Customizing Individual Toasts Source: https://context7.com/fkhadra/react-toastify/llms.txt Demonstrates how to customize a toast's appearance and behavior using an options object, including position, duration, and callbacks. ```tsx import { toast } from 'react-toastify'; tost("Custom notification", { position: "bottom-right", autoClose: 3000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, pauseOnFocusLoss: true, draggable: true, theme: "colored", type: "success", toastId: "unique-id-123", onOpen: () => console.log("Toast opened"), onClose: (reason) => console.log("Toast closed:", reason) }); ``` -------------------------------- ### Basic Toast Notification Source: https://github.com/fkhadra/react-toastify/blob/main/README.md Demonstrates how to set up a basic toast notification with a button trigger and the ToastContainer component. ```jsx import React from 'react'; import { ToastContainer, toast } from 'react-toastify'; function App(){ const notify = () => toast("Wow so easy!"); return (
); } ``` -------------------------------- ### TypeScript Configuration for Bundling Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md Configuration for tsup to bundle the library. It specifies loaders for CSS files, treating them as raw text. ```typescript loader: { '.css': 'text' } ``` -------------------------------- ### Importing the Raw Stylesheet Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md The raw stylesheet can be imported directly for custom styling solutions. ```css import 'react-toastify/dist/ReactToastify.css'; ``` -------------------------------- ### Format Code with Prettier Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md Applies Prettier formatting to the source files in the `src/` directory. ```bash pnpm prettier ``` -------------------------------- ### Displaying a Loading Toast Source: https://context7.com/fkhadra/react-toastify/llms.txt Shows how to display a persistent loading toast that can be dismissed programmatically. Useful for indicating ongoing asynchronous operations. ```tsx import { toast } from 'react-toastify'; // Show loading toast - won't auto-close const loadingId = toast.loading("Please wait..."); // Later, dismiss the loading toast tost.dismiss(loadingId); ``` -------------------------------- ### Run a Single Cypress Component Test Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md Executes a specific Cypress component test file headlessly in Chrome. Replace the spec path with the desired test file. ```bash pnpm exec cypress run --component -b chrome --spec src/components/Toast.cy.tsx ``` -------------------------------- ### Core Store Singleton Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md The `store.ts` module exports a module-level singleton that manages container state and a render queue for toasts. ```typescript import { containerObserver } from './core/containerObserver'; import { renderQueue } from './core/renderQueue'; const containers = new Map(); const renderQueue = new RenderQueue(); ``` -------------------------------- ### Displaying Different Toast Types Source: https://context7.com/fkhadra/react-toastify/llms.txt Shows how to render success, error, warning, info, and dark theme notifications using built-in types. ```tsx import { toast } from 'react-toastify'; // Success notification tost.success("Operation completed successfully!"); // Error notification tost.error("Something went wrong!"); // Warning notification tost.warning("Please check your input"); // Info notification tost.info("New update available"); // Dark theme toast tost.dark("Dark mode notification"); ``` -------------------------------- ### Use Notification Center Hook Source: https://context7.com/fkhadra/react-toastify/llms.txt Build a persistent notification center with read/unread tracking using the `useNotificationCenter` hook. Optional initial data, custom sorting, and filtering can be provided. ```tsx import { useNotificationCenter, NotificationCenterItem } from 'react-toastify/addons/use-notification-center'; import { toast, ToastContainer } from 'react-toastify'; interface NotificationData { title: string; text: string; } function NotificationCenter() { const { notifications, unreadCount, markAsRead, markAllAsRead, remove, clear, add, find, sort } = useNotificationCenter({ // Optional: provide initial data data: [], // Optional: custom sort (default: newest first) sort: (a, b) => b.createdAt - a.createdAt, // Optional: filter notifications filter: (item) => item.data?.hidden !== true }); return (

Notifications ({unreadCount} unread)

{notifications.map((notification) => (

{notification.data?.title}

{notification.data?.text}

))}
); } ``` -------------------------------- ### Subscribe to Toast Lifecycle Events Source: https://context7.com/fkhadra/react-toastify/llms.txt Listen for toast lifecycle events (added, updated, removed) by using `toast.onChange()`. Remember to call the returned unsubscribe function when no longer needed. ```tsx import { toast, ToastItem } from 'react-toastify'; const unsubscribe = toast.onChange((payload: ToastItem) => { switch (payload.status) { case "added": console.log("New toast:", payload.id, payload.content); break; case "updated": console.log("Toast updated:", payload.id); break; case "removed": console.log("Toast removed:", payload.id, "reason:", payload.reason); break; } }); // Later, unsubscribe unsubscribe(); ``` -------------------------------- ### Utilize Built-in Toast Transitions Source: https://context7.com/fkhadra/react-toastify/llms.txt Choose from four built-in transition animations: Bounce, Slide, Zoom, and Flip. These can be set as the default on the `ToastContainer` or overridden on a per-toast basis. ```tsx import { ToastContainer, toast, Bounce, Slide, Zoom, Flip } from 'react-toastify'; // Set default transition on container // Or override per-toast ttoast("Bouncing!", { transition: Bounce }); ttoast("Sliding!", { transition: Slide }); ttoast("Zooming!", { transition: Zoom }); ttoast("Flipping!", { transition: Flip }); ``` -------------------------------- ### ToastContainer Configuration Options Source: https://context7.com/fkhadra/react-toastify/llms.txt Configure the `ToastContainer` with various props to control position, autoClose, theme, animations, limits, and more. This sets default behavior for all toasts. ```tsx import { ToastContainer, Slide } from 'react-toastify'; function App() { return ( e.altKey && e.code === 'KeyT'} nonce="csp-nonce-value" /> ); } ``` -------------------------------- ### React Server Components Directive Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md All bundles are prefixed with this directive to ensure compatibility with React Server Components. ```javascript "use client"; ``` -------------------------------- ### Create Custom Transitions with cssTransition Source: https://context7.com/fkhadra/react-toastify/llms.txt Define custom enter and exit animations for toasts using the `cssTransition` utility. This allows integration with CSS animation libraries like animate.css. ```tsx import { cssTransition, ToastContainer, toast } from 'react-toastify'; // Using animate.css classes const CustomAnimation = cssTransition({ enter: "animate__animated animate__fadeInUp", exit: "animate__animated animate__fadeOutDown", appendPosition: false, collapse: true, collapseDuration: 300 }); function App() { return ( <> ); } ``` -------------------------------- ### Run Cypress Component Tests Headlessly Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md Executes Cypress component tests in a headless mode, suitable for CI environments. ```bash pnpm test:run ``` -------------------------------- ### Toast Transition Component Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md Manages animations for toasts using predefined transitions like Bounce, Flip, Slide, and Zoom, built with the `cssTransition` utility. ```typescript import { cssTransition } from '../utils/cssTransition'; const bounce = cssTransition({ ... }); export const Transitions = ({ type, ...props }) => { switch (type) { case 'bounce': return ; // ... other transitions } }; ``` -------------------------------- ### Basic Toast Display with React-Toastify Source: https://context7.com/fkhadra/react-toastify/llms.txt Displays a simple notification using the toast() function. Ensure ToastContainer is rendered in your app. ```tsx import { ToastContainer, toast } from 'react-toastify'; function App() { const notify = () => toast("Wow so easy!"); return (
); } ``` -------------------------------- ### Container Observer Instance Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md Each `ToastContainer` instance has a corresponding `ContainerObserver` responsible for managing its state, including the toast map, queue, and lifecycle callbacks. ```typescript export class ContainerObserver { // ... toast map, waiting queue, snapshot for useSyncExternalStore onOpen?: () => void; onClose?: () => void; } ``` -------------------------------- ### Render Custom React Components as Toast Content Source: https://context7.com/fkhadra/react-toastify/llms.txt Display custom React components as toast content. The component receives `closeToast` and `toastProps`, and can access custom data passed via the `data` prop. ```tsx import { toast, ToastContentProps } from 'react-toastify'; interface NotificationData { title: string; message: string; } function CustomToast({ closeToast, toastProps, data }: ToastContentProps) { return (

{data.title}

{data.message}

); } ttoast(CustomToast, { data: { title: "New Message", message: "You have a new notification" }, autoClose: false, closeButton: false }); ``` -------------------------------- ### Using the Unstyled Subpath Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md Import `ToastContainer` from the `unstyled` subpath to use the raw component without injected styles. This is useful when providing custom CSS. ```typescript import { ToastContainer } from 'react-toastify/unstyled'; ``` -------------------------------- ### Imperative Toast API Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md The `toast.ts` module provides the public imperative API for dispatching toast notifications. ```typescript export const toast = { success: (message: Args[0], options?: Args[1]) => dispatch(ToastType.SUCCESS, message, options), // ... other methods like update, promise, onChange }; ``` -------------------------------- ### Pause and Play Toasts Programmatically Source: https://context7.com/fkhadra/react-toastify/llms.txt Use `toast.pause()` and `toast.play()` to control toast timers. You can pause/resume all toasts, specific toasts by ID, or toasts within a specific container. ```tsx import { toast } from 'react-toastify'; // Pause all toasts ttoast.pause(); // Pause specific toast ttoast.pause({ id: "my-toast-id" }); // Pause all toasts in a container ttoast.pause({ containerId: "my-container" }); // Resume all toasts ttoast.play(); // Resume specific toast ttoast.play({ id: "my-toast-id" }); ``` -------------------------------- ### Handling Promises with React-Toastify Source: https://context7.com/fkhadra/react-toastify/llms.txt Automatically displays pending, success, or error notifications based on the resolution or rejection of a promise. Supports string messages or render functions for advanced customization. ```tsx import { toast } from 'react-toastify'; // Simple usage with strings const fetchData = () => fetch('/api/data').then(res => res.json()); tost.promise(fetchData, { pending: 'Fetching data...', success: 'Data loaded successfully! 👌', error: 'Failed to load data 🤯' }); // Advanced usage with render functions and custom data interface UserData { name: string; } const createUser = (): Promise => fetch('/api/users', { method: 'POST' }).then(res => res.json()); tost.promise(createUser, { pending: { render: () => "Creating user...", icon: false }, success: { render: ({ data }) => `Welcome, ${data.name}!`, icon: "🎉" }, error: { render: ({ data }) => `Error: ${data.message}` } }); ``` -------------------------------- ### Using Multiple Toast Containers Source: https://context7.com/fkhadra/react-toastify/llms.txt Render multiple `ToastContainer` components with unique `containerId` props to manage toasts in different areas of your application. Toasts can then be directed to a specific container. ```tsx import { ToastContainer, toast } from 'react-toastify'; function App() { return ( <> ); } // Send toast to specific container ttoast("Regular notification", { containerId: "notifications" }); ttoast.error("Critical alert!", { containerId: "alerts" }); ``` -------------------------------- ### Toast Container Hook Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md The `useToastContainer` hook serves as the sole bridge between the React component tree and the toast notification system, utilizing `useSyncExternalStore` for efficient updates. ```typescript import { useSyncExternalStore } from 'react'; import { containerObserver } from '../core/containerObserver'; export const useToastContainer = (containerId: ContainerId) => { const observer = containerObserver.get(containerId); const state = useSyncExternalStore(observer.subscribe, observer.getSnapshot); // ... rest of the hook logic }; ``` -------------------------------- ### Programmatically Dismissing Toasts Source: https://context7.com/fkhadra/react-toastify/llms.txt Provides methods to dismiss toasts individually using their ID, all toasts within a specific container, or all toasts globally. ```tsx import { toast } from 'react-toastify'; const toastId = toast("Will be dismissed"); // Dismiss a specific toast tost.dismiss(toastId); // Dismiss all toasts in a specific container tost.dismiss({ containerId: "my-container" }); // Dismiss toast by id in specific container tost.dismiss({ id: toastId, containerId: "my-container" }); // Dismiss all toasts everywhere tost.dismiss(); ``` -------------------------------- ### Notification Center Hook Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md The `useNotificationCenter()` hook provides a persistent notification store independent of the transient toast queue. It captures lifecycle events via `toast.onChange()` and supports filtering, read/unread status, and sorting. ```typescript import { useNotificationCenter } from 'react-toastify/addons/use-notification-center'; function App() { const { notifications, clear } = useNotificationCenter(); return (
{notifications.map(n => (
{n.content}
))}
); } ``` -------------------------------- ### Individual Toast Component Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md The `Toast` component wraps each individual toast and manages its specific behaviors like drag-to-dismiss, pause-on-hover, and timer functionality, consuming the `useToast` hook. ```typescript import { useToast } from './useToast'; export const Toast = ({ toastId, ...props }: ToastProps) => { const { isHovering, isFocused, isDismissed, pause, resume } = useToast(toastId); // ... render toast content, progress bar, close button }; ``` -------------------------------- ### Toast Container Component Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md The `ToastContainer` component handles positioning, stacking, keyboard focus, and hotkey management. It computes CSS variable transforms in a layout effect. ```typescript export const ToastContainer = (props: ToastContainerProps) => { // ... positioning, stacking logic, Alt+T hotkey return
{/* Toasts will be rendered here */}
; }; ``` -------------------------------- ### Updating an Existing Toast Source: https://context7.com/fkhadra/react-toastify/llms.txt Dynamically updates the content, type, or options of a toast that has already been displayed. Can also render custom React components. ```tsx import { toast } from 'react-toastify'; // Create initial toast const toastId = toast("Processing...", { autoClose: false }); // Update with new content and type tost.update(toastId, { render: "Operation complete!", type: "success", autoClose: 5000 }); // Update with a React component tost.update(toastId, { render: ({ data }) => , data: { status: "complete" } }); ``` -------------------------------- ### Control Progress Bar Manually Source: https://context7.com/fkhadra/react-toastify/llms.txt Manually control the progress bar for custom indicators like upload progress. Initialize with `autoClose: false` and update the `progress` property using `toast.update()`. ```tsx import { toast } from 'react-toastify'; // Create toast with controlled progress (0-1) const toastId = toast("Uploading...", { progress: 0, autoClose: false }); // Update progress as upload proceeds const updateProgress = (percent: number) => { toast.update(toastId, { progress: percent / 100 }); }; // Mark as done (will close the toast) ttoast.done(toastId); ``` -------------------------------- ### Clear Waiting Queue Source: https://context7.com/fkhadra/react-toastify/llms.txt Clear pending toasts from the queue when using the `limit` option. Only displayed toasts will remain after clearing. ```tsx import { ToastContainer, toast } from 'react-toastify'; // Container with limit // Toasts beyond limit are queued for (let i = 0; i < 10; i++) { toast(`Toast ${i}`, { containerId: "limited" }); } // Clear all queued toasts (only displayed ones remain) tost.clearWaitingQueue({ containerId: "limited" }); ``` -------------------------------- ### Runtime CSS Injection with useStyleSheet Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md The useStyleSheet hook handles runtime CSS injection, ensuring that CSS is injected only once per document, even across multiple ToastContainer instances. It is designed to be safe for Shadow DOM and iframes. If a later mount provides a nonce, the attribute on the existing style tag is updated. ```typescript if (isBrowser) { const { document } = window; if (!document.getElementById(id)) { const style = document.createElement('style'); style.id = id; style.setAttribute('type', 'text/css'); if (nonce) { style.setAttribute('nonce', nonce); } style.innerHTML = css; document.head.appendChild(style); } else if (nonce && !document.getElementById(id).getAttribute('nonce')) { document.getElementById(id).setAttribute('nonce', nonce); } } ``` -------------------------------- ### Clearing Waiting Queue Source: https://github.com/fkhadra/react-toastify/blob/main/CLAUDE.md Use `toast.clearWaitingQueue()` to drain the per-container queue of excess toasts. This is useful when managing a large number of notifications. ```typescript toast.clearWaitingQueue() ``` -------------------------------- ### Checking if a Toast is Active Source: https://context7.com/fkhadra/react-toastify/llms.txt Allows checking if a toast with a specific ID is currently displayed, useful for preventing duplicate notifications. Can also check within a specific container. ```tsx import { toast } from 'react-toastify'; const toastId = "unique-id"; // Prevent duplicate toasts if (!toast.isActive(toastId)) { toast("New notification", { toastId }); } // Check in specific container const isActive = toast.isActive(toastId, "my-container"); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.