Search code examples
reactjsreact-hooksreact-toastify

How can i use react-toastify from hook?


I found useToast and useToastContainer, but documentation is absent and i don't understand how tu use these hooks. Can anyone provide some info about these hooks?


Solution

  • The toasts inherit ToastContainer’s props. Props defined on toast supersede ToastContainer’s props.

    There are two ways you can use toasts in your application:

    1. Define ToastContainer inside the component

    import { ToastContainer, toast } from 'react-toastify';
    import 'react-toastify/dist/ReactToastify.css';
      
      const App = () => {
        notify = () => toast("Wow so easy !");
    
        return (
          <div>
            <button onClick={notify}>Notify !</button>
    
            // You can add <ToastContainer /> in root component as well.
            <ToastContainer />
          </div>
        );
      }
    

    2. Call toast.configure() once in your app. At the root of your app is the best place.

    The library will mount a ToastContainer for you if none is mounted.

    import { toast } from "react-toastify";
    import 'react-toastify/dist/ReactToastify.css';
      
       // Call it once in your app. At the root of your app is the best place
      toast.configure()
      
      const App = () => {
        notify = () => toast("Wow so easy !");
    
        return (
            <button onClick={notify}>Notify !</button>
        );
      }
    
    

    You can use either of them. I prefer the 2nd method because you only need to define toast.configure() which is quite clean way to add it.

    You can add configuration as per your need like below:

    toast.configure({
      autoClose: 8000,
      draggable: false,
      //etc you get the idea
    });
    

    EDIT

    If you want to use toast hooks, then you must wrap your app with the ToastProvider to have access to its context elsewhere within your app.

    import { ToastProvider, useToasts } from 'react-toast-notifications'
    
    const FormWithToasts = () => {
      const { addToast } = useToasts()
    
      const onSubmit = async value => {
        const { error } = await dataPersistenceLayer(value)
    
        if (error) {
          addToast(error.message, { appearance: 'error' })
        } else {
          addToast('Saved Successfully', { appearance: 'success' })
        }
      }
    
      return <form onSubmit={onSubmit}>...</form>
    }
    
    const App = () => (
      <ToastProvider>
        <FormWithToasts />
      </ToastProvider>
    )