Closed Stophface closed 10 months ago
Hi @Stophface,
There is no method in the react-toastify package for getting the count of visible toasts. However you can use simple DOM practices to find out if there are any toasts visible.
There are two methods:-
You can check for ToastContainer existence by finding the div with class name 'Toastify__toast-container'. Note:- These class names are given automatically by react-toastify and these divs are created inside ToastifyContainer which you add as an component in react after importing it from react-toastify.
const checkForToastContainer = (e) => {
// check for toast container
const toastContainer = document.querySelector(".Toastify__toast-container");
if (toastContainer) {
console.log("There is a toastContainer");
} else {
console.log("No toastContainer");
}
e.preventDefault();
};
You can count the toast blocks by finding all the divs with class name 'Toastify__toast'.
const checkForNumOfToasts = (e) => {
e.preventDefault();
const toastContainer = document.getElementsByClassName("Toastify__toast");
const numOfToasts = toastContainer.length;
console.log(numOfToasts);
};
Here's an example using the above methods in a simple react app. For styles I used Bootstrap CDN.
import { ToastContainer } from "react-toastify";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
function App() {
const getToast = (e) => {
e.preventDefault();
toast.error("this is an error");
};
const checkForToastContainer = (e) => {
// check for toast container
e.preventDefault();
const toastContainer = document.querySelector(".Toastify__toast-container");
if (toastContainer) {
console.log("There is a toastContainer");
} else {
console.log("No toastContainer");
}
};
const checkForNumOfToasts = (e) => {
e.preventDefault();
const toastContainer = document.getElementsByClassName("Toastify__toast");
console.log(toastContainer.length);
};
return (
<div className="App container pt-2">
<ToastContainer />
<button className="btn btn-dark getToast m-1" onClick={getToast}>
Get a Toast
</button>
<button
className="btn btn-primary getToast m-1"
onClick={checkForToastContainer}
>
Check for ToastContainer
</button>
<button
className="btn btn-success getToast m-1"
onClick={checkForNumOfToasts}
>
Get number of toasts running
</button>
</div>
);
}
export default App;
Perfect, thanks!
Is there a way to get the current count of visible toasts? Is there a way to find out, if any toast is currently showing?
I am using