Search code examples
javascripttoastr

It's there a way to close a toast with an external event?


I have a react component that wraps some content that it's not available in screens under 1024px if the user resizes the screen an event will be triggered opening a toast that only can be closed clicking it, but if the user resizes up the resolution again I want to close this toast automatically. It's there a way to force a specific toast to close assigning some kind of id to find it and clicking it with javascript?

// this calls a generic function that opens a toast.
manageWarning('', 'You are running on a small screen resolution, this feature it\'s only available on screens up to 1024 px, please scale up the window again', true);

// This is the generic function
export function manageWarning(id, message, disableAutoClose) {
    toastr.options.timeOut = disableAutoClose ? 0 : Global.MESSAGE_ERROR_DURATION;
    toastr.options.extendedTimeOut = disableAutoClose ? 0 : toastr.options.extendedTimeOut;
    toastr.warning(message);
}

Solution

  • I managed to fix it with some changes to my code base.

    The manage warning method now returns the toast itself

    export function manageWarning(id, message, disableAutoClose) {
        toastr.options.timeOut = disableAutoClose ? 0 : Global.MESSAGE_ERROR_DURATION;
        toastr.options.extendedTimeOut = disableAutoClose ? 0 : 
        toastr.options.extendedTimeOut;
        return toastr.warning(message);
    }
    

    Now the consumer can save the reference of this toast

    this.toast = manageWarning('', 'You are running on a small screen resolution, this feature it\'s only available on screens up to 1024 px, please scale up the window again', true);
    

    With this in mind now I can just simply call

    this.toast.fadeIn(); // Method to show the toast again.
    this.toast.fadeOut(); // Method close the toast.