Published: April 11 2020

React Hooks + Bootstrap - Alert Notifications

Tutorial built with React 16.13.1 and Bootstrap 4.4.1

Other versions available:

Alert notifications are an extremely common requirement in web applications for displaying status messages to the user e.g. error, success, warning and info alerts.

This tutorial shows how to implement a simple reusable alert component using React Hooks, Bootstrap CSS and RxJS. The example has two pages, one with a single react bootstrap alert component and the other with multiple bootstrap alerts displayed in separate sections.

For more info about how to use RxJS to send messages and communicate between React components see React + RxJS - Communicating Between Components with Observable & Subject.

For more info about bootstrap alerts you can find the official docs here, the example only uses the bootstrap CSS classes so you can ignore the "javascript behavior" section of the bootstrap docs, the example uses React to handle behavior.

The example project code is available on GitHub at

Here it is in action:(See on StackBlitz at

Running the React Hooks + Bootstrap Alerts Example Locally

  1. Install NodeJS and NPM from
  2. Download or clone the tutorial project source code from
  3. Install all required npm packages by running npm install from the command line in the project root folder (where the package.json is located).
  4. Start the application by running npm start from the command line in the project root folder, this will build the application and automatically launch it in the browser on the URL http://localhost:8080.

For more info on setting up a React development environment see React - Setup Development Environment.

Adding Bootstrap Alerts to Your React App

To add bootstrap alerts to your React application you'll need to copy the following files from the example project:

  • _components/Alert.jsx - the alert component is responsible for displaying alerts.
  • _services/alert.service.js - the alert service can be used by any react component or service to send alerts to alert components.

Ensure your project has the required node package dependencies

This is the list of dependencies from the example application that are required by the react alert component and service:

    "dependencies": {
        "prop-types": "^15.7.2",
        "react": "^16.13.1",
        "react-dom": "^16.13.1",
        "react-router-dom": "^5.1.2",
        "rxjs": "^6.5.5"

Define your react routes using a <BrowserRouter> component

Inside your react app component (or wherever you have your routes defined), use the <BrowserRouter> component to define your routes, this includes the browser history object so the alert component can listen for route changes and automatically clear alerts. The alert component accesses the history object with the useHistory hook from the React Router library.

See line 10 below from the example react hooks app component.

import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';

import { Alert } from '../_components';
import { Home } from '../home';
import { MultiAlerts } from '../multi-alerts';

function App() {
    return (

export { App }; 

Import and add the <Alert /> component where you want alerts to be displayed

Add the alert component tag wherever you want alert messages to be displayed.

Alert Component Options

  • The alert component accepts optional id and fade attributes:
    • id - used if you want to display multiple alerts in different locations (see the Multiple Alerts page in the example above). An alert component with an id attribute will display any messages sent to the alert service with a matching id, e.g. alertService.error('something broke!', { id: 'left-alert' }); will send an error message to the alert component with id="left-alert". Defaults to default-alert.
    • fade - controls if alert messages are faded out when closed. Defaults to true.

The app component in the example /src/app/App.jsx contains a global Alert tag without an id above the Route tags, this alert displays any messages sent to the alert service without an id specified, e.g. alertService.success('you won!'); will send a success message to the global alert without an id.

Lines 4 and 20 below from the example app show how to add the react alert component.

import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';

import { Alert } from '../_components';
import { Home } from '../home';
import { MultiAlerts } from '../multi-alerts';

function App() {
    return (
            {/* nav */}
            <div className="container text-center">
                <Link to="/" className="btn btn-link">Single Alert</Link>
                <Link to="/multi-alerts" className="btn btn-link">Multiple Alerts</Link>

            {/* main app container */}
            <div className="jumbotron p-4">
                <div className="container text-center">
                    <Alert />
                    <Route exact path="/" component={Home} />
                    <Route path="/multi-alerts" component={MultiAlerts} />

export { App };

Displaying Bootstrap Alert Notifications in Your React App

Once you've added support for bootstrap alerts to your react app by following the previous steps, you can trigger alert notifications from any component by simply importing the alert service and calling one of it's methods for displaying different types of bootstrap alerts: success(), error(), info() and warn().

React Alert Service Options

  • The first parameter to each alert method is a string for the alert message which can be a plain text string or HTML
  • The second parameter is an optional options object that supports an autoClose boolean property and keepAfterRouteChange boolean property:
    • autoClose - if true tells the alert component to automatically close the bootstrap alert after three seconds. Default is false.
    • keepAfterRouteChange - if true prevents the bootstrap alert from being closed after one route change, this is handy for displaying messages after a redirect such as a successful registration message. Default is false.

Here is the home component from the example app that sends example notification messages to the alert service when each of the buttons is clicked. In a real world application alert notifications can be triggered by any type of event, for example an error from an http request or a success message after user registers a new account.

import React, { useState } from 'react';

import { alertService } from '../_services';

function Home() {
    const [options, setOptions] = useState({
        autoClose: false,
        keepAfterRouteChange: false

    function handleOptionChange(e) {
        const { name, checked } =;
        setOptions(options => ({ ...options, [name]: checked }));

    return (
            <h1>React Hooks + Bootstrap Alerts</h1>
            <button className="btn btn-success m-1" onClick={() => alertService.success('Success!!', options)}>Success</button>
            <button className="btn btn-danger m-1" onClick={() => alertService.error('Error :(', options)}>Error</button>
            <button className="btn btn-info m-1" onClick={() =>'Some info....', options)}>Info</button>
            <button className="btn btn-warning m-1" onClick={() => alertService.warn('Warning: ...', options)}>Warn</button>
            <button className="btn btn-outline-dark m-1" onClick={() => alertService.clear()}>Clear</button>
            <div className="form-group mt-2">
                <div className="form-check">
                    <input type="checkbox" className="form-check-input" name="autoClose" id="autoClose" checked={options.autoClose} onChange={handleOptionChange} />
                    <label htmlFor="autoClose">Auto close alert after three seconds</label>
                <div className="form-check">
                    <input type="checkbox" className="form-check-input" name="keepAfterRouteChange" id="keepAfterRouteChange" checked={options.keepAfterRouteChange} onChange={handleOptionChange} />
                    <label htmlFor="keepAfterRouteChange">Keep displaying after one route change</label>

export { Home };



Breakdown of the React Hooks + Boostrap Alert Code

Below is a breakdown of the pieces of code used to implement the bootstrap alerts example with React Hooks, you don't need to know the details of how it all works to use the alerts in your project, it's only if you're interested in the nuts and bolts or if you want to modify the code or behaviour.

React Alert Service

The alert service (/src/app/_services/alert.service.js) acts as the bridge between any component in an React application and the alert component that actually displays the bootstrap alert notifications. It contains methods for sending, clearing and subscribing to alert messages.

The AlertType object defines the types of alerts allowed in the application.

The service uses the RxJS Observable and Subject classes to enable communication with other React components, for more information on how this works see React + RxJS - Communicating Between Components with Observable & Subject.

import { Subject } from 'rxjs';
import { filter } from 'rxjs/operators';

const alertSubject = new Subject();
const defaultId = 'default-alert';

export const alertService = {

export const AlertType = {
    Success: 'Success',
    Error: 'Error',
    Info: 'Info',
    Warning: 'Warning'

// enable subscribing to alerts observable
function onAlert(id = defaultId) {
    return alertSubject.asObservable().pipe(filter(x => x && === id));

// convenience methods
function success(message, options) {
    alert({ ...options, type: AlertType.Success, message });

function error(message, options) {
    alert({ ...options, type: AlertType.Error, message });

function info(message, options) {
    alert({ ...options, type: AlertType.Info, message });

function warn(message, options) {
    alert({ ...options, type: AlertType.Warning, message });

// core alert method
function alert(alert) { = || defaultId;;

// clear alerts
function clear(id = defaultId) {{ id });

React Hooks + Bootstrap Alert Component

The alert component (/src/app/_components/Alert.jsx) controls the adding & removing of bootstrap alerts in the UI, it maintains an array of alerts that are rendered in the template returned by the React Hooks function component.

The useEffect() hook is used to subscribe to the observable returned from the alertService.onAlert() method, this enables the alert component to be notified whenever an alert message is sent to the alert service and add it to the alerts array for display. Sending an alert with an empty message to the alert service tells the alert component to clear the alerts array. The useEffect() hook is also used to register a route change listener by calling history.listen() which automatically clears alerts on route changes.

The empty dependency array [] passed as a second parameter to the useEffect() hook causes the react hook to only run once when the component mounts, similar to the componentDidMount() method in a traditional react class component. The function returned from the useEffect() hook cleans up the subscribtions when the component unmounts, similar to the componentWillUnmount() method in a traditional react class component.

The removeAlert() method removes the specified alert object from the array, it allows individual bootstrap alerts to be closed in the UI.

The cssClass() method returns a corresponding bootstrap alert class for each of the alert types, if you're using something other than bootstrap you could change the CSS classes returned to suit your application.

The returned JSX template renders a bootstrap alert message for each alert in the alerts array.

import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import PropTypes from 'prop-types';

import { alertService, AlertType } from '../_services';

const propTypes = {
    id: PropTypes.string,
    fade: PropTypes.bool

const defaultProps = {
    id: 'default-alert',
    fade: true

function Alert({ id, fade }) {
    const history = useHistory();
    const [alerts, setAlerts] = useState([]);

    useEffect(() => {
        // subscribe to new alert notifications
        const subscription = alertService.onAlert(id)
            .subscribe(alert => {
                // clear alerts when an empty alert is received
                if (!alert.message) {
                    setAlerts(alerts => {
                        // filter out alerts without 'keepAfterRouteChange' flag
                        const filteredAlerts = alerts.filter(x => x.keepAfterRouteChange);

                        // remove 'keepAfterRouteChange' flag on the rest
                        filteredAlerts.forEach(x => delete x.keepAfterRouteChange);
                        return filteredAlerts;
                } else {
                    // add alert to array
                    setAlerts(alerts => ([...alerts, alert]));

                    // auto close alert if required
                    if (alert.autoClose) {
                        setTimeout(() => removeAlert(alert), 3000);

        // clear alerts on location change
        const historyUnlisten = history.listen(() => {

        // clean up function that runs when the component unmounts
        return () => {
            // unsubscribe & unlisten to avoid memory leaks
    }, []);

    function removeAlert(alert) {
        if (fade) {
            // fade out alert
            const alertWithFade = { ...alert, fade: true };
            setAlerts(alerts => => x === alert ? alertWithFade : x));

            // remove alert after faded out
            setTimeout(() => {
                setAlerts(alerts => alerts.filter(x => x !== alertWithFade));
            }, 250);
        } else {
            // remove alert
            setAlerts(alerts => alerts.filter(x => x !== alert));

    function cssClasses(alert) {
        if (!alert) return;

        const classes = ['alert', 'alert-dismissable'];
        const alertTypeClass = {
            [AlertType.Success]: 'alert alert-success',
            [AlertType.Error]: 'alert alert-danger',
            [AlertType.Info]: 'alert alert-info',
            [AlertType.Warning]: 'alert alert-warning'


        if (alert.fade) {

        return classes.join(' ');

    if (!alerts.length) return null;

    return (
        <div className="container">
            <div className="m-3">
                {, index) =>
                    <div key={index} className={cssClasses(alert)}>
                        <a className="close" onClick={() => removeAlert(alert)}>&times;</a>
                        <span dangerouslySetInnerHTML={{__html: alert.message}}></span>

Alert.propTypes = propTypes;
Alert.defaultProps = defaultProps;
export { Alert };


Need Some React Help?

Search fiverr for freelance React developers.

Follow me for updates

On Twitter or RSS.

When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Supported by