Toastr can be easily integrated into your project using npm or yarn. For npm:
npm install toastr
For yarn:
yarn add toastr
After installation, import Toastr into your JavaScript file:
import toastr from 'toastr';
or if you are using a CDN, include the Toastr CSS and JavaScript files in your HTML <head>
:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
Toastr provides a simple and consistent API for displaying notifications. The most basic usage involves calling one of the four core functions: success
, info
, warning
, and error
. Each function accepts a message as its first argument and an optional title as its second argument.
// Display a success message
.success('This is a success toast!');
toastr
// Display an info message with a title
.info('This is an info toast!', 'Information');
toastr
// Display a warning message
.warning('This is a warning toast!');
toastr
// Display an error message with a title
.error('This is an error toast!', 'Error!'); toastr
These functions will display a toast notification with a default appearance.
Toastr offers extensive configuration options to customize the appearance and behavior of notifications. These options can be set globally or individually for each toast. Here are some key options:
positionClass
: Determines the position of the toast on the screen. Options include toast-top-right
, toast-top-center
, toast-top-full-width
, toast-top-left
, toast-bottom-right
, toast-bottom-center
, toast-bottom-full-width
, and toast-bottom-left
. Defaults to toast-top-right
.
closeButton
: (Boolean) Whether to display a close button on each toast. Defaults to true
.
debug
: (Boolean) Displays additional debugging information in the console. Defaults to false
.
newestOnTop
: (Boolean) Whether the newest toasts should appear on top. Defaults to true
.
progressBar
: (Boolean) Whether to display a progress bar on each toast. Defaults to false
.
preventDuplicates
: (Boolean) Prevents duplicate toasts from being displayed. Defaults to false
.
timeOut
: (Integer) The duration (in milliseconds) that a toast remains visible before automatically closing. Defaults to 5000
(5 seconds).
extendedTimeOut
: (Integer) The duration (in milliseconds) that a toast remains visible when the mouse hovers over it. Defaults to 1000
(1 second).
showEasing
, hideEasing
, showMethod
, hideMethod
: These options control the animation effects when toasts appear and disappear. See the Toastr documentation for a full list of supported values.
You can set these options globally using toastr.options
:
.options = {
toastr"closeButton": true,
"debug": false,
"newestOnTop": false,
"progressBar": true,
"positionClass": "toast-top-center",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
; }
For more detailed information and a complete list of configuration options, please refer to the official Toastr documentation.
Toastr provides four built-in toast types, each with a distinct visual style to convey different message severities: success, info, warning, and error. In addition, you can create fully custom toasts.
Success toasts indicate successful operations or positive outcomes. They typically use a green background and a checkmark icon (depending on the theme).
.success('Your changes have been saved!'); toastr
This will display a success toast with a default message and appearance. You can customize the message and use options like title
to add more detail.
.success('File uploaded successfully!', 'Upload Complete'); toastr
Info toasts provide neutral information or updates to the user. They often have a light blue background.
.info('New data has been received.'); toastr
Similar to success toasts, you can provide a title to add context:
.info('Server status updated.', 'System Information'); toastr
Warning toasts alert the user to potential issues or situations requiring attention. These typically display with a yellow background.
.warning('Your password is weak. Please change it.'); toastr
Again, you can add a title for clarity:
.warning('Low disk space detected.', 'System Warning'); toastr
Error toasts indicate failures or errors that require user action. They generally use a red background and may include an error icon.
.error('An error occurred. Please try again later.'); toastr
Titles are helpful in providing more specific error details:
.error('Failed to connect to the server.', 'Connection Error'); toastr
For more advanced customization beyond the standard toast types and configuration options, you can create custom toasts. This usually involves creating a custom HTML structure and using the toastr.info
(or any other core function) with the html
option set to true
. Remember to style your custom toast appropriately using CSS.
const customToast = `
<div>
<span class="custom-icon">!</span>
<span class="custom-message">This is a custom toast message.</span>
</div>
`;
.info(customToast, 'Custom Toast', { html: true }); toastr
Remember to include relevant CSS to style the custom-icon
and custom-message
elements to achieve the desired look and feel. This approach allows for the greatest degree of control over your toast notifications’ appearance and functionality.
This section covers more advanced techniques for using Toastr to create highly customized and interactive notifications.
As previously discussed, Toastr’s behavior and appearance are heavily customizable via the toastr.options
object. This allows you to globally set options like positionClass
, timeOut
, closeButton
, progressBar
, preventDuplicates
, and various animation properties (showEasing
, hideEasing
, showMethod
, hideMethod
). Remember that these options can be overridden on a per-toast basis by passing an options object as the third argument to the toast functions (e.g., toastr.success('Message', 'Title', { timeOut: 10000 })
).
Toastr offers several predefined positions for toasts, selected using the positionClass
option. These include options like toast-top-right
, toast-top-center
, etc. You can further customize positioning and styling by directly manipulating the CSS of the toast container and individual toast elements using your own stylesheets. Inspect the generated HTML structure of the toasts to identify the classes and elements you need to target.
While Toastr doesn’t inherently include icons, you can easily add them using various methods. One common approach is to include an icon font (like Font Awesome) in your project and then add the relevant icon class to your custom toast HTML (using the html: true
option as described in the Custom HTML Content section). Alternatively, you can embed images directly into your custom toast HTML.
The progressBar
option (set to true
in toastr.options
) adds a progress bar to each toast, visually indicating the remaining time before it automatically closes. The progress bar’s styling can be customized using CSS.
By default, toasts include a close button allowing users to dismiss them manually. You can disable this behavior by setting closeButton
to false
in toastr.options
or the individual toast options.
The preventDuplicates
option, when set to true
, prevents multiple toasts with the same message from appearing. This is particularly useful for preventing redundant notifications. Note that duplicate detection is based on the message text; if you need more sophisticated duplicate detection, you may need a custom implementation.
As shown earlier, using the html: true
option allows you to inject arbitrary HTML into your toasts. This empowers you to create richly formatted and interactive notifications. Remember to carefully escape any user-supplied content to prevent cross-site scripting (XSS) vulnerabilities.
Toastr doesn’t directly expose extensive callback functions. However, you can achieve similar functionality by observing the DOM changes related to toast creation and removal. Use JavaScript event listeners to detect when toasts are shown, hidden, or clicked. Libraries like MutationObserver can be helpful for monitoring changes in the DOM related to Toastr. This advanced approach requires a deeper understanding of JavaScript and DOM manipulation. You could, for instance, monitor for additions of specific Toastr class elements within your toast container to know when a new toast has appeared.
This section details how to integrate Toastr into various JavaScript frameworks and handle server-side rendering (SSR).
Toastr is a relatively lightweight library that integrates well with popular JavaScript frameworks. The specific integration approach varies slightly depending on the framework:
React:
In React, you’d typically use Toastr within a component. Import the library and call the Toastr functions directly within your component’s logic. You can manage state within your component to control when toasts appear.
import React, { useState } from 'react';
import toastr from 'toastr';
function MyComponent() {
const [message, setMessage] = useState('');
const handleClick = () => {
.success('Action completed!');
toastrsetMessage('Toast displayed!');
;
}
return (
<div>
<button onClick={handleClick}>Trigger Toast</button>
<p>{message}</p>
</div>
;
) }
Remember to include the Toastr CSS and JavaScript files as described in the Getting Started section, either via CDN or a bundler like Webpack.
Angular:
In Angular, you can inject Toastr into your services or components. You might create a service dedicated to managing notifications.
import { Injectable } from '@angular/core';
import * as toastr from 'toastr';
Injectable({
@: 'root'
providedIn
})export class ToastService {
showSuccess(message: string) {
.success(message);
toastr
}// ... other toast methods
}
Then inject this service into your components and call its methods to display toasts. Make sure to include Toastr in your angular.json
file.
Vue:
In Vue, you can use Toastr directly within your Vue components. Import the library and call the Toastr methods. For example:
<template>
<button @click="showToast">Show Toast</button>
</template>
<script>
import toastr from 'toastr';
export default {
methods: {
showToast() {
toastr.info('This is a Vue toast!');
}
}
};
</script>
As with React, ensure that you have included Toastr’s CSS and JS files in your project.
General Framework Notes: For any framework, manage Toastr’s CSS conflicts carefully. Ensure that your framework’s styling doesn’t interfere with Toastr’s default styles, and vice-versa. Consider using CSS modules or scoping to avoid conflicts.
When using Toastr in applications with server-side rendering, you’ll need to ensure that the Toastr JavaScript is loaded and executed on the client-side after the initial HTML is rendered. Simply including Toastr in your server-rendered HTML will likely not work correctly. Instead, you should:
Load Toastr on the client: Include the Toastr JavaScript file (or the appropriate module import) only within your client-side JavaScript bundle.
Hydration: Ensure that your framework properly hydrates the client-side application after the initial server render. This allows the client-side JavaScript, including Toastr, to take over and manage the interaction with the DOM.
Conditional Rendering: Only render Toastr-related components or display toasts on the client-side. This helps to avoid issues with the server trying to interact with the browser’s DOM.
Effectively, treat Toastr as a client-side-only library when working with SSR. Your server-side code should only generate the initial HTML; the actual toast display logic should be entirely client-side.
This section provides guidance on resolving common issues and debugging Toastr in your application.
Toasts not appearing: This is often due to incorrect inclusion of the Toastr CSS and JavaScript files, or conflicts with other JavaScript libraries or CSS styles. Ensure the files are correctly linked in your HTML <head>
and that there are no CSS conflicts overriding Toastr’s styles. Check your browser’s developer console for JavaScript errors.
Incorrect positioning: Verify that you’ve set the positionClass
option correctly in toastr.options
or as individual toast options. Double-check your CSS for any conflicting styles that might be affecting the toast positioning.
Animation issues: If toasts appear or disappear unexpectedly or with incorrect animations, inspect your CSS for any conflicting or incorrectly applied animation styles. Ensure that the showEasing
, hideEasing
, showMethod
, and hideMethod
options are correctly set and compatible with your CSS animations.
Duplicate toasts: If duplicate toasts are appearing despite setting preventDuplicates: true
, ensure that the messages being used for the toasts are truly identical, including whitespace and casing. The duplicate prevention mechanism relies on exact string matching.
Custom HTML issues: When using custom HTML, ensure that your HTML is correctly formatted and that all necessary CSS is included to style the custom elements properly. Also, always sanitize any user-supplied content within custom HTML to prevent XSS vulnerabilities.
Conflicting JavaScript Libraries: Toastr may conflict with other JavaScript libraries that also manipulate the DOM or manage notifications. Try disabling other libraries temporarily to see if it resolves the issue.
SSR Issues: If you’re using server-side rendering (SSR), refer to the SSR section in this manual to correctly load and use Toastr in your client-side JavaScript.
Browser Developer Console: The browser’s developer console (usually accessed by pressing F12) is your primary debugging tool. Check for JavaScript errors, warnings, or other messages that might indicate the source of the problem. Network tab can help check if the JS and CSS files are being loaded correctly.
Simplify your code: To isolate the problem, create a minimal, reproducible example that demonstrates the issue. Remove unnecessary code to pinpoint the source of the error.
Inspect the DOM: Use your browser’s developer tools to inspect the HTML structure generated by Toastr. This helps identify any unexpected elements or styling issues.
Check CSS specificity: If your custom CSS styles aren’t overriding Toastr’s default styles, make sure that your CSS selectors are specific enough to target the correct elements. Use the browser’s developer tools to check the computed styles of the toast elements.
Test in a different browser: Sometimes, issues are browser-specific. Test your application in multiple browsers to see if the problem is browser-dependent.
Use a simpler theme (if applicable): If you’re using a custom theme, try switching to the default Toastr theme to rule out any issues with your theme’s styling.
timeOut
and extendedTimeOut
options in toastr.options
to control the duration toasts are visible.remove()
method.newestOnTop
option in toastr.options
. If it’s false
, newer toasts will appear below older ones.timeOut
value to reduce the number of simultaneously visible toasts. Adjusting positioning and the preventDuplicates
setting may also help.If you encounter problems not covered here, please consult the official Toastr documentation or search online forums for solutions. Providing specific details about your setup and the issue you’re facing will help others assist you more effectively.
This section details the core API functions and the global configuration options available in Toastr.
toastr.success(message, title, options)
Displays a success toast notification.
message
(string): The main message to be displayed in the toast. Required.title
(string, optional): An optional title displayed above the message.options
(object, optional): An object containing options to customize the toast’s appearance and behavior. See the toastr.options
section for details. These options override the global toastr.options
settings for this specific toast.toastr.info(message, title, options)
Displays an info toast notification.
message
(string): The main message to be displayed. Required.title
(string, optional): An optional title.options
(object, optional): An object containing options to customize the toast. Overrides global toastr.options
.toastr.warning(message, title, options)
Displays a warning toast notification.
message
(string): The main message. Required.title
(string, optional): An optional title.options
(object, optional): An object containing options. Overrides global toastr.options
.toastr.error(message, title, options)
Displays an error toast notification.
message
(string): The main message. Required.title
(string, optional): An optional title.options
(object, optional): An object containing options. Overrides global toastr.options
.toastr.clear()
Clears all currently displayed toasts.
toastr.remove(toast)
Removes a specific toast from the display. toast
should be a reference to the toast element (typically obtained through DOM manipulation). Note that this function is less commonly used; toastr.clear()
is often sufficient for most use cases.
toastr.options
A global configuration object that sets default options for all subsequent toast notifications. The following options can be set:
closeButton
(boolean): Whether to show a close button (default: true
).debug
(boolean): Enable debug mode (default: false
).newestOnTop
(boolean): Whether newer toasts should appear on top (default: true
).progressBar
(boolean): Whether to show a progress bar (default: false
).positionClass
(string): Specifies the toast’s position (e.g., toast-top-right
, toast-bottom-left
; default: toast-top-right
).preventDuplicates
(boolean): Prevents duplicate toasts (default: false
).onclick
(function): A callback function executed when a toast is clicked.showDuration
(integer): Show animation duration in milliseconds (default: 300
).hideDuration
(integer): Hide animation duration in milliseconds (default: 1000
).timeOut
(integer): Duration before toast automatically closes in milliseconds (default: 5000
).extendedTimeOut
(integer): Duration toast remains visible on hover in milliseconds (default: 1000
).showEasing
(string): Easing function for the show animation.hideEasing
(string): Easing function for the hide animation.showMethod
(string): Animation method for showing the toast.hideMethod
(string): Animation method for hiding the toast.tapToDismiss
(boolean): Whether tapping/clicking dismisses the toast (default: true
).Modifying toastr.options
affects all subsequent calls to toastr.success
, toastr.info
, toastr.warning
, and toastr.error
unless overridden by options passed directly to those functions.