skip to Main Content

I want to create a toast with two buttons "accept" and "reject".
when I click reject I want to dismiss the only toast which contains these two buttons.

i simply want the toast to disappear when i click the reject button inside the toast.

Here is my custom toat with callingToast component-

const toastId = toast(CallingToast, {
      ...toastOptions,
      autoClose: 60000,
      closeButton: false,
      pauseOnHover: false,
      closeOnClick: false,
    });

Below is my calling toast component-

import React from 'react';
import { toast } from 'react-toastify';

export default function CallingToast() {
  return (
    <>
      <button>accept</button>
      <button
        onClick={}
      >
        reject
      </button>
    </>
  );
}

I tried calling toast.dismiss() on the reject butto, but it dismisses all of the toast which I don’t want.

I also tried passing toastId to the component somehow but it obviously didn’t work. I couldn’t find any related questions as well that’s why posting my own.

2

Answers


  1. Chosen as BEST ANSWER

    So, I am answering my own question because after some digging and lots of trial and error. I finally found the solution to my problem.

    I found out during my research that if you render a component inside toast then that component automatically receives closeToast and toastProps as props.

    So in CallingToast component, When the reject button is clicked i called closeToast() function and it did the work.

    import React from 'react';
    import { toast } from 'react-toastify';
    
    export default function CallingToast({closeToast}) {
      return (
        <>
          <button>accept</button>
          <button
            onClick={closeToast()}
          >
            reject
          </button>
        </>
      );
    }
    

    Only if documentation was a little better it would have saved me a lot of time.


  2. If you call toast.dismiss without argument, all the displayed toasts will be removed. An id is always returned each time you display a toast so use that to remove a toast programmatically by calling toast.dismiss(id).

    Here is the example taken from the documentation

    import React from 'react';
    import { toast } from 'react-toastify';
    
    function Example(){
      const toastId = React.useRef(null);
    
      const notify = () => toastId.current = toast("Lorem ipsum dolor");
    
      const dismiss = () =>  toast.dismiss(toastId.current);
    
      const dismissAll = () =>  toast.dismiss();
    
      return (
        <div>
          <button onClick={notify}>Notify</button>
          <button onClick={dismiss}>Dismiss</button>
          <button onClick={dismissAll}>Dismiss All</button>
        </div>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search