npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

complete-react-toast

v0.0.2

Published

Hook y componentes de Toast dinámicos, versátiles y accesibles para React

Readme

complete-react-toast

npm bundlephobia types tree-shaking

Sistema de toasts dinámico y versátil para React. API funcional y declarativa, totalmente accesible y personalizable.

🚀 Instalación

npm install complete-react-toast
# o
pnpm add complete-react-toast
# o
yarn add complete-react-toast

📖 Uso básico

1. Configurar el Provider

import { ToastProvider, Toaster } from 'complete-react-toast';

function App() {
  return (
    <ToastProvider>
      <MyApplication />
      <Toaster /> {/* Renderiza los toasts automáticamente */}
    </ToastProvider>
  );
}

2. Usar toasts en componentes

import { useToast } from 'complete-react-toast';

function MyComponent() {
  const toast = useToast();

  const handleSuccess = () => {
    toast.success('¡Operación exitosa!');
  };

  const handleError = () => {
    toast.error('Algo salió mal', {
      duration: 5000,
      action: {
        label: 'Reintentar',
        onClick: () => console.log('Reintentando...')
      }
    });
  };

  return (
    <div>
      <button onClick={handleSuccess}>Éxito</button>
      <button onClick={handleError}>Error</button>
    </div>
  );
}

🔧 API

useToast()

Hook principal que retorna la API completa:

const toast = useToast();

// Tipos básicos
toast.success('Mensaje de éxito');
toast.error('Mensaje de error');
toast.warning('Mensaje de advertencia');
toast.info('Mensaje informativo');
toast.loading('Cargando...');

// Toast personalizado
toast.custom('Mensaje personalizado', {
  type: 'info',
  position: 'bottom-center',
  duration: 3000
});

// Gestión
toast.dismiss('toast-id');
toast.dismissAll();
toast.update('toast-id', 'Nuevo mensaje', { type: 'success' });

Opciones de Toast

| Propiedad | Tipo | Default | Descripción | | ------------- | --------------------- | ------------- | --------------------------------------------- | | type | ToastType | "info" | Tipo de toast (success, error, warning, etc.) | | duration | number | 4000 | Duración en ms (0 = no auto-dismiss) | | dismissible | boolean | true | Si se puede cerrar manualmente | | position | ToastPosition | "top-right" | Posición en pantalla | | variant | ToastVariant | "filled" | Variante de estilo | | icon | ReactNode | auto | Icono personalizado | | action | { label, onClick } | undefined | Botón de acción | | data | Record<string, any> | undefined | Datos adicionales | | onClose | () => void | undefined | Callback al cerrar |

Posiciones disponibles

type ToastPosition =
  | "top-left" | "top-center" | "top-right"
  | "bottom-left" | "bottom-center" | "bottom-right";

Variantes de estilo

type ToastVariant = "filled" | "outlined" | "minimal";

📋 Ejemplos avanzados

Manejo de errores automático

import { useToast, useToastError } from 'complete-react-toast';

function ApiComponent() {
  const toast = useToast();
  const withToastError = useToastError();

  // Método manual
  const handleSave = async () => {
    try {
      await api.saveData(data);
      toast.success('Datos guardados');
    } catch (error) {
      toast.error(`Error: ${error.message}`);
    }
  };

  // Método automático con wrapper
  const handleSaveAuto = withToastError(
    async () => {
      await api.saveData(data);
      return 'Datos guardados correctamente';
    },
    {
      successMessage: (result) => result,
      errorMessage: (error) => `Error al guardar: ${error.message}`,
      loadingMessage: 'Guardando datos...'
    }
  );

  return (
    <div>
      <button onClick={handleSave}>Guardar (manual)</button>
      <button onClick={handleSaveAuto}>Guardar (automático)</button>
    </div>
  );
}

Toast de progreso/loading

function UploadComponent() {
  const toast = useToast();

  const handleUpload = async () => {
    const id = toast.loading('Subiendo archivo...', {
      duration: 0, // No auto-dismiss
      dismissible: false
    });

    try {
      // Simular progreso
      setTimeout(() => {
        toast.update(id, 'Procesando archivo...', {
          icon: '⚙️'
        });
      }, 1000);

      await uploadFile();

      toast.update(id, '¡Archivo subido exitosamente!', {
        type: 'success',
        duration: 3000,
        dismissible: true
      });
    } catch (error) {
      toast.update(id, `Error: ${error.message}`, {
        type: 'error',
        duration: 5000,
        dismissible: true
      });
    }
  };

  return <button onClick={handleUpload}>Subir archivo</button>;
}

Configuración personalizada

function CustomToastApp() {
  return (
    <ToastProvider
      config={{
        defaultPosition: 'bottom-center',
        defaultVariant: 'outlined',
        maxToasts: 3,
        defaultDuration: 6000,
        pauseOnHover: true,
        gap: 12,
        offset: { x: 20, y: 20 }
      }}
    >
      <App />
      <Toaster />
    </ToastProvider>
  );
}

Toasts con configuración predefinida

function NotificationComponent() {
  const apiToast = useToastWithDefaults({
    position: 'top-left',
    variant: 'minimal',
    duration: 8000
  });

  return (
    <button onClick={() => apiToast.info('Notificación de API')}>
      Toast personalizado
    </button>
  );
}

Containers específicos

function MultiPositionApp() {
  return (
    <ToastProvider>
      <App />

      {/* Containers individuales para control específico */}
      <ToastContainer position="top-right" className="notifications" />
      <ToastContainer position="bottom-center" className="alerts" />
    </ToastProvider>
  );
}

Toast con JSX personalizado

function CustomContentToast() {
  const toast = useToast();

  const showCustom = () => {
    toast.custom(
      <div>
        <strong>¡Nueva actualización!</strong>
        <p>La versión 2.0 está disponible</p>
      </div>,
      {
        duration: 0,
        action: {
          label: 'Actualizar',
          onClick: () => window.location.reload()
        },
        icon: '🎉'
      }
    );
  };

  return <button onClick={showCustom}>Mostrar actualización</button>;
}

✨ Características

  • API Dual: Componentes y hooks funcionales
  • TypeScript: Tipado completo y extensible
  • Accesible: ARIA labels, roles y live regions
  • Animaciones: Transiciones suaves CSS-in-JS
  • Sin dependencias: CSS embebido, sin hojas de estilo externas
  • Configurable: Posiciones, duraciones, límites, estilos
  • Performante: Render optimizado y gestión de memoria
  • SSR Safe: Compatible con Next.js, Gatsby, etc.
  • Tree-shakeable: Solo importa lo que usas
  • Minimalista: < 3KB gzipped

🎨 Personalización

Estilos CSS personalizados

// Los toasts usan estilos en línea, pero puedes sobrescribirlos
<ToastContainer
  className="my-custom-toasts"
  style={{
    // Estilos del container
  }}
/>

Iconos personalizados

const toast = useToast();

toast.success('¡Éxito!', {
  icon: <CustomSuccessIcon />
});

toast.error('Error', {
  icon: '🚨'
});

🌐 Compatibilidad

  • React ≥18
  • TypeScript ≥4.7
  • Navegadores modernos (ES2020+)
  • SSR/SSG compatible

🤝 Comparación con alternativas

| Característica | complete-react-toast | react-hot-toast | react-toastify | | -------------------- | -------------------- | --------------- | -------------- | | Tamaño | ~3KB | ~4KB | ~8KB | | TypeScript nativo | ✅ | ✅ | ⚠️ | | API funcional | ✅ | ✅ | ⚠️ | | Sin dependencias CSS | ✅ | ❌ | ❌ | | Múltiples posiciones | ✅ | ❌ | ✅ | | Wrapper de errores | ✅ | ❌ | ❌ | | Configuración global | ✅ | ⚠️ | ✅ |

💡 Casos de uso

  • 🔔 Notificaciones: Mensajes de sistema y usuario
  • ⚠️ Alertas: Errores, advertencias y confirmaciones
  • 📊 Feedback: Resultado de operaciones CRUD
  • 🔄 Loading: Estados de carga y progreso
  • 🎯 Onboarding: Guías y tips contextuales
  • 📱 Mobile-first: Notificaciones responsivas

🔗 Recursos adicionales