Rate this docs

React Bootstrap Alerts MDB Pro component

React Alerts - Bootstrap 4 & Material Design

React Bootstrap alerts are feedback messages which are displayed after specific actions preceded by the user. Length of the text is not limited.

To improve the communication between your website/application and its users, you might want to consider adding some automatic pop-up messages.

With the right use of colors, they add some emotional weight to our information, ranging from a simple warning to critical system failure or from an operation success to a neutral information.


Basic examples MDB Pro component

Info message Warning message Success message Error message



import React, { Component } from 'react';
import { Button, ToastContainer, toast } from 'mdbreact';

class AlertPage extends Component {
  notify(type){
  return () => {
    switch (type) {
      case 'info':
        toast.info('Info message', {
          autoClose: 3000
        });
        break;
      case 'success':
        toast.success('Success message', {
          position: "top-right",
        });
        break;
      case 'warning':
        toast.warn('Warning message');
        break;
      case 'error':
        toast.error('Error message');
        break;
    }
  };
};
  render(){
    return (
      <React.Fragment>
        <button className='btn btn-info' onClick={this.notify('info')}>Info</button>
        <button className='btn btn-success' onClick={this.notify('success')}>Success</button>
        <button className='btn btn-warning' onClick={this.notify('warning')}>Warning</button>
        <button className='btn btn-danger' onClick={this.notify('error')}>Error</button>
        <ToastContainer
          hideProgressBar={true}
          newestOnTop={true}
          autoClose={5000}
        />
      </React.Fragment>
    );
  }
}
export default AlertPage;

Basics

The alert consists of two elements: toast, which is a method used to programmatically trigger an alert, and a ToastContainer that is required to host the toast. To use either make sure you have probably imported them first:


        import { toast, ToastContainer } from 'mdbreact';
      

Options

Each of the aforementioned indgredients for an alert serves as an entry-point for its customization. toast() method accepts two arguments, first one being our message (or a JSX component to be rendered in its place), while the second is an option object. The object's properties below.

Key Type Default Description
position string top-right One of top-right, top-center, top-left, bottom-right, bottom-center, bottom-left
autoClose false or int 5000 Delay in ms to close the toast. If set to false, the notification need to be closed manualy
closeButton React Element or false - A React Component to replace the default close button or false to hide the button
transition function - A reference to a valid react-transition-group/Transition component
hideProgressBar bolean false Display or not the progress bar below the toast(remaining time)
pauseOnHover bolean true Keep the timer running or not on hover
closeOnClick bolean true Dismiss toast on click
newestOnTop bolean false Display newest toast on top
className string - Add optional classes to the container
style object - Add optional inline style to the container
toastClassName string - Add optional classes to the toast
bodyClassName string - Add optional classes to the toast body
progressClassName string - Add optional classes to the progress bar
dragabble string/object - Allow toast to be draggable
draggablePercent number 80 The percentage of the toast's width it takes for a drag to dismiss a toast(value between 0 and 100)

There is also the second way to apply options to the toast alerts. The keys of the option object discussed above represent consecutive props of the ToastContainer component, that in turn accept values specified in the table. Beside being able to define toast alert customization otherwise than on a toast-to-toast basis, this option input offers few features unavailable to the toast() method.

Props Type Default Description
newestOnTop boolean false Changes the order of incoming toasts
Right to left layout boolean false Changes layout inside the toasts to properly render content in languages with right-to-left writing system

Toast options supersede ToastContainer props.


Rendering a component

The alerts obviously support content that is of string type, but in fact they go far beyond that: they allow you to render your own components! It is enough to just past them as the first argument of the toast() function. Remember: when rendering a component, a closeToast function is passed as a props. It is used to trigger closing the alert on user interaction.

import React from 'react';
import { ToastContainer, toast } from "mdbreact";

const Msg = ({ closeToast }) => (
    <div>
      Lorem ipsum dolor
      <button>Retry</button>
      <button onClick={closeToast}>Close</button>
    </div>
)

const App = () => (
    <div>
      <button onClick={() => toast(<Msg />)}>Hello 😀</button>
      <ToastContainer />
    </div>
);

Programmatic removal

Every time a toast is displayed, an id is returned. Calling toast.dissmiss(id) removes a toast; calling the function with no arguments dissmisses all the toasts.

import React, { Component } from 'react';
import { toast } from 'react-toastify';

class Example extends Component {
  toastId = null;

  notify = () => this.toastId = toast("Lorem ipsum dolor");

  dismiss = () => toast.dismiss(this.toastId);

  dismissAll = () => toast.dismiss();

  render(){
    return (
      <React.Fragment>
        <button onClick={this.notify}>Notify</button>
        <button onClick={this.dismiss}>Dismiss</button>
        <button onClick={this.dismissAll}>Dismiss All</button>
      </React.Fragment>
    );
  }
}

Updating a toast

Alert's options are inherited at render, but there is an easy way to update it using... the update() function. Take a look:


import React, { Component } from 'react';
import { toast } from 'react-toastify';

class Update extends Component {
    toastId = null;

  notify = () => this.toastId = toast("Hello", { autoClose: false });

  update = () => toast.update(this.toastId, { type: "info", autoClose: 5000 });

  render(){
        return (
          <React.Fragment>
            <button onClick={this.notify}>Notify</button>
            <button onClick={this.update}>Update</button>
          </React.Fragment>
      )
  }
}

Among the alert's features open for alteration is its content. You can access is under the render key inside the update() function.


// With a string
toast.update(this.toastId, {
  render: "New content"
  type: "info",
  autoClose: 5000
});

// Or with a component
toast.update(this.toastId, {
  render: <MyComponent />
  type: "info",
  autoClose: 5000
});

Prevent duplicates

To prevent duplicates, you can check if a given toast is active by calling toast.isActive(id) like the snippet below. With this approach, you can decide with more precision whether or not you want to display a toast.


import React, { Component } from 'react';
import { toast } from 'mdbreact';

class Example extends Component {
  toastId = null;

  notify = () => {
    if (! toast.isActive(this.toastId)) {
      this.toastId = toast("I cannot be duplicated !");
    }
  }

  render(){
    return (
      <div>
        <button onClick={this.notify}>Notify</button>
      </div>
    );
  }
}

Transition

There is 4 built-in transition provided:

  • Bounce
  • Slide
  • Zoom
  • Flip
Bounce is applied by default, but you can apply any of them:


import { Slide, Zoom, Flip, Bounce } from 'mdbreact';

  <ToastContainer
    transition={Slide}
  />
//...
  <ToastContainer
    transition={YourCustomTransition}
  />
                      

...But you can define your own transition! The toast relies on react-transition-group for the enter and exit transition, therefore any transition built with it is fine! Let's take a look at how an animation is defined is, using zoom animation from animate.css as an example.


/* style.css*/
@keyframes zoomIn {
  from {
    opacity: 0;
    transform: scale3d(.3, .3, .3);
  }

  50% {
    opacity: 1;
  }
}

.zoomIn {
  animation-name: zoomIn;
}

@keyframes zoomOut {
  from {
    opacity: 1;
  }

  50% {
    opacity: 0;
    transform: scale3d(.3, .3, .3);
  }

  to {
    opacity: 0;
  }
}

.zoomOut {
  animation-name: zoomOut;
}

/* Not needed with the cssTransition helper */

.animate {
  animation-duration: 800ms;
}

The easiest way to roll your own transition is by using the cssTransition helper, which allows us to skip ahead all the react-transition-group-related hussle. Only thing needed here are the enter and exit class names. The transition duration is set to 750ms by default but it can be overridden:


import React, { Component } from 'react';
import { toast, cssTransition } from 'mdbreact';
import './style.css';

const Zoom = cssTransition({
  enter: 'zoomIn',
  exit: 'zoomOut',
  // default to 750ms, can be omitted
  duration = 750,
  // to have different times of exit / entry, pass in an Array
});

class App extends Component {
  notify = () => {
    toast("ZoomIn and ZoomOut", {
      transition: Zoom,
      autoClose: 5000
    });
  };

  render(){
      return <button onClick={this.notify}>Notify</button>;
  }
}

Some transitions are based on the toast position. If you pass appendPosition to the cssTransition helper as shown below, the current position will be appended to the enter and exit class name:


import React, { Component } from 'react';
import { toast, cssTransition } from 'mdbreact';
import './style.css';

const Zoom = cssTransition({
    // zoomIn will become zoomIn--top-right or zoomIn--top-left and so on
    enter: 'zoomIn',
    // zoomIn will become zoomOut--top-right or zoomOut--top-left and so on
    exit: 'zoomOut',
    // default to false
    appendPosition: true
});

class App extends Component {
    notify = () => {
      toast("ZoomIn and ZoomOut", {
        transition: Zoom,
        autoClose: 5000
      });
    };

  render(){
      return <button onClick={this.notify}>Notify</button>;
  }
}

Ultimately, you may want to define transition yourself, from scratch. Note: in that case you will need the react-transition-group.


import React, { Component } from 'react';
import { toast } from 'mdbreact';
import Transition from 'react-transition-group/Transition';
import './style.css';

const ZoomInAndOut = ({ children, position, ...props }) => (
    <Transition
    {...props}
    {/* Same as the animation duration */}
    timeout={800}
    onEnter={ node => node.classList.add('zoomIn', 'animate')}
    onExit={node => {
      node.classList.remove('zoomIn', 'animate');
      node.classList.add('zoomOut', 'animate');
    }}
  >
    {children}
  </Transition>
);

class App extends Component {
  notify = () => {
    toast("ZoomIn and ZoomOut", {
      transition: ZoomInAndOut,
      autoClose: 5000
    });
  };

  render(){
    return <button onClick={this.notify}>Notify</button>;
  }
}
    
Parameter Type Required Default Description
enter string ✓ - The class name that will be used when the toast enter
exit string ✓ - The class name that will be used when the toast exit
duration number| Array ✘ 750 The transition duration in ms.
appendPosition bool ✘ false Append or not the position to the class name: yourClassName--top-right, yourClassName--bottom-left...

Alert creator MDB Pro component

Alert creator

Features
Position
Toast Type

Can also be changed on toast using the type option.


Within a method:
                        
Container options:
                            

Default Bootstrap alerts


<div className="alert alert-primary" role="alert">
  A simple primary alert—check it out!
</div>
<div className="alert alert-secondary" role="alert">
  A simple secondary alert—check it out!
</div>
<div className="alert alert-success" role="alert">
  A simple success alert—check it out!
</div>
<div className="alert alert-danger" role="alert">
  A simple danger alert—check it out!
</div>
<div className="alert alert-warning" role="alert">
  A simple warning alert—check it out!
</div>
<div className="alert alert-info" role="alert">
  A simple info alert—check it out!
</div>
<div className="alert alert-light" role="alert">
  A simple light alert—check it out!
</div>
<div className="alert alert-dark" role="alert">
  A simple dark alert—check it out!
</div>