Ask Question

How to programmatically close the Chakra-UI toast?

I want to control the closing behaviour of a Chakra-UI toast programmatically. In the current documentation (v0.8) I could find the API (doc)



AuthorΒ΄s Anki Batsukh image

Anki Batsukh

Last edited on

1 Answer available

Best answer

So after long research I think I found a workaround for that issue.

Chakra offers you a possibility to render a custom toast via render property. From the passed object you can grab the onClose function which you can call in order to close the toast! Therefore we will save that function in a ref. With that you are able to call it where you want πŸ˜‰
Do not forget to set duration: null since we do not want that the toast closes automatically ^^

function Example() {
  const toast = useToast();
  const toastRefs = React.useRef([]);

  return (
        onClick={() =>
            position: "bottom-left",
            duration: null,
            render: ({ onClose }) => {

              return (
                <Box m={3} color="white" p={3} bg="blue.500">
                  Hello World
        Show Toast
      <Button onClick={() => {
          toastRefs.current.forEach(cb => cb());
          toastRefs.current = [];
        Close Toast

As you may already know the Chakra team is already working on the v1 so I think the new API will solve this issue. Until then this solution should be sufficient.

Last edited on