How To Use react-hot-toast In React Js

In this article, we will learn how to use react-hot-toast in React JS.

The react-hot-toast notification provides any type of message like a success message, a warning message, and an error message. if you have to use this module first install this module using NPM.

Using the below command you can use testify,

npm install react-hot-toast

You can see below how to import and how to basic use of this,

import React from 'react'
import toast, { Toaster } from 'react-hot-toast';

export default function toasthottoast() {
  const notify = () => {
    toast('Hello World', {
      duration: 4000,
      position: 'top-right',
    });
  }
  return (
    <div>
      <Toaster />
      <button onClick={() => notify()}>Make me a toast</button>
    </div>
  )
}

Now we can learn about react-hot-toast modules,

toast()

you can use toast is anywhere but you can add <Toaster /> in your app first. you can see below toast options.

toast('Norification', {
  duration: 1000,
  position: 'top-right',
  // Styling
  style: {},
  className: '',
  // Custom Icon
  icon: '👏',
  // Change colors of success/error/loading icon
  iconTheme: {
    primary: '#000',
    secondary: '#fff',
  },
  // Aria
  ariaProps: {
    role: 'status',
    'aria-live': 'polite',
  },
});

You can also create a different type of toast like below,

//blank
toast('Notification');

//Success
toast.success('Success');

//error
toast.error('Error');

//custom
toast.custom(<div>Custom</div>);

//loading
toast.loading('Loading');

//promise
const myPromise = fetchData();
toast.promise(myPromise, {
  loading: 'Loading',
  success: 'Success',
  error: 'Erro',
});

toaster()

This component is render all toasts. you can see below all options,

<Toaster
  position="top-right"
  reverseOrder={false}
  gutter={8}
  containerClassName=""
  containerStyle={{}}
  toastOptions={{
    // Define default options
    className: '',
    duration: 3000,
    style: {
      background: '#363636',
      color: '#fff',
    },
    // Default options for specific types
    success: {
      duration: 3000,
      theme: {
        primary: 'green',
        secondary: 'black',
      },
    },
  }}
/>

You can also use the custom render function like below,

import { Toaster, resolveValue } from 'react-hot-toast';
// In your app
<Toaster>
  {(t) => (
    <div
      style={{ opacity: t.visible ? 1 : 0, background: 'white', padding: 5 }}
    >
      {resolveValue(t.message, t)}
    </div>
  )}
</Toaster>;

<ToastBar />

You can use this function with a toaster custom render function like below you can see available options of that,

<ToastBar
  toast={t}
  style={{}} // Overwrite styles
  position="top-right" // Used to adapt the animation
/>

You can add custom toastbar like below,

import { toast, Toaster, ToastBar } from 'react-hot-toast';
<Toaster>
  {(t) => (
    <ToastBar toast={t}>
      {({ icon, message }) => (
        <>
          {icon}
          {message}
          {t.type !== 'loading' && (
            <button onClick={() => toast.dismiss(t.id)}>X</button>
          )}
        </>
      )}
    </ToastBar>
  )}
</Toaster>;

useToaster()

Using this hook creates a headless system that handles notification state management for you. This features auto-dismiss, pause on hover, and an unmount delay for exit animations, as well as keeping track of all toast made with toast(). you can see an example below,

const Notifications = () => {
  const { toasts, handlers } = useToaster();
  const { startPause, endPause } = handlers;
  return (
    <div onMouseEnter={startPause} onMouseLeave={endPause}>
      {toasts
        .filter((toast) => toast.visible)
        .map((toast) => (
          <div key={toast.id} {...toast.ariaProps}>
            {toast.message}
          </div>
        ))}
    </div>
  );
};
// Create toasts anywhere
toast('Hello World');

useToasterStore()

This hook allows you to access the internal status of the toaster. This is the best option if you require data access but don’t want to roll your own toaster. you can use like below,

import { useToasterStore } from "react-hot-toast";
const { toasts, pausedAt } = useToasterStore();

You can see some results below,

 

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories