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)

chakra

3739 views

AuthorΒ΄s AnkiCodes image

AnkiCodes

πŸ‘€
1
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 (
    <>
      <Button
        onClick={() =>
          toast({
            position: "bottom-left",
            duration: null,
            render: ({ onClose }) => {
              toastRefs.current.push(onClose);

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

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.