How to use Toast from blueprintjs with hooks?

494 views Asked by At

I get trouble to use Toast from blueprintjs I succeed to display it, but when I click on the cross the toast doesn't close and the timeout doesn't work.

enter image description here

This is my code:

<Toaster position={Position.TOP}>
      <Toast message="Votre message a bien été envoyé." className="text-lime-800" timeout={3000}/>
 </Toaster>

The documentation explains that I have to link my toaster with a Reference, but I don't understand why :/ I tried to create one like this:

const toaster = useRef(null);
...
<Toaster position={Position.TOP} ref={toaster}>
      <Toast message="Votre message a bien été envoyé." className="text-lime-800" timeout={3000}/>
 </Toaster>

But it doesn't change anything.

Could you help me pls ?

2

There are 2 answers

0
Adi Dahiya On

If you use the <Toaster><Toast>...</Toast></Toaster> API to render toast components directly, then you are responsible for maintaining state for the currently displayed list of toasts. <Toaster> will not automatically hide its children Toasts for you; you will have to remove them from the React tree. This is demonstrated in the "React component usage" documentation section.

0
Diego Laucsen On

I've a solution.

First, create your ref using useRef

const toaster = useRef(null);

Then, connect into your Toast component:

<Toaster ref={toaster} />

Later, you have to do a trick before show a new toast. When you should call show normally, do this:

if (!!toaster && !!toaster.current) {
  const toasterInstance = toaster.current as ToasterInstance;
  toasterInstance.show({
    ...
  });
}

That worked for me, I hope it can help you.