Toastr - Documentation

Getting Started

Installation

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>

Basic Usage

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
toastr.success('This is a success toast!');

// Display an info message with a title
toastr.info('This is an info toast!', 'Information');

// Display a warning message
toastr.warning('This is a warning toast!');

// Display an error message with a title
toastr.error('This is an error toast!', 'Error!');

These functions will display a toast notification with a default appearance.

Configuration Options

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:

You can set these options globally using toastr.options:

toastr.options = {
  "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.

Toast Types

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

Success toasts indicate successful operations or positive outcomes. They typically use a green background and a checkmark icon (depending on the theme).

toastr.success('Your changes have been saved!');

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.

toastr.success('File uploaded successfully!', 'Upload Complete');

Info Toasts

Info toasts provide neutral information or updates to the user. They often have a light blue background.

toastr.info('New data has been received.');

Similar to success toasts, you can provide a title to add context:

toastr.info('Server status updated.', 'System Information');

Warning Toasts

Warning toasts alert the user to potential issues or situations requiring attention. These typically display with a yellow background.

toastr.warning('Your password is weak. Please change it.');

Again, you can add a title for clarity:

toastr.warning('Low disk space detected.', 'System Warning');

Error Toasts

Error toasts indicate failures or errors that require user action. They generally use a red background and may include an error icon.

toastr.error('An error occurred. Please try again later.');

Titles are helpful in providing more specific error details:

toastr.error('Failed to connect to the server.', 'Connection Error');

Custom Toasts

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>
`;

toastr.info(customToast, 'Custom Toast', { html: true });

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.

Advanced Usage

This section covers more advanced techniques for using Toastr to create highly customized and interactive notifications.

Options and Customization

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 })).

Positioning and Styling

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.

Adding Icons

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.

ProgressBar

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.

Close Button

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.

Prevent Duplicates

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.

Custom HTML Content

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.

Callbacks and Events

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.

Integration

This section details how to integrate Toastr into various JavaScript frameworks and handle server-side rendering (SSR).

Integrating with Frameworks (React, Angular, Vue)

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 = () => {
    toastr.success('Action completed!');
    setMessage('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({
  providedIn: 'root'
})
export class ToastService {
  showSuccess(message: string) {
    toastr.success(message);
  }
  // ... 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.

Server-Side Rendering (SSR)

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:

  1. Load Toastr on the client: Include the Toastr JavaScript file (or the appropriate module import) only within your client-side JavaScript bundle.

  2. 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.

  3. 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.

Troubleshooting

This section provides guidance on resolving common issues and debugging Toastr in your application.

Common Issues

Debugging Tips

Frequently Asked Questions (FAQ)

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.

API Reference

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.

toastr.info(message, title, options)

Displays an info toast notification.

toastr.warning(message, title, options)

Displays a warning toast notification.

toastr.error(message, title, options)

Displays an error toast notification.

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:

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.