Implementing notifications in React with Reapop
Tags: react, webdev
Published: 2023-02-23 18:15:51

**Written by [Lawrence Eagles](https://blog.logrocket.com/author/lawrenceoputa/)✏️**

According to the [2020 Stack Overflow developer study](https://survey.stackoverflow.co/2022/#section-most-popular-technologies-web-frameworks-and-technologies), React is ranked as the second most used web development framework behind Node.js. Because of React’s popularity, many libraries have been developed for React. 

In this article, we'll learn about the Reapop API and build a simple React app to implement notifications with Reapop. To get the most out of this article, you will need Node.js installed in your system and a basic knowledge of [JavaScript and React](https://blog.logrocket.com/javascript-concepts-before-learning-react/). Let’s get started! 

_Jump ahead:_

*   [Getting started in React with the Reapop API](#getting-started-reapop-api)
    *   [Entities](#entities)
    *   [Actions](#actions)
    *   [Hooks](#hooks)
    *   [Components](#components)
    *   [Helpers](#helpers)
    *   [Themes](#themes)
*   [Implementing notifications with Reapop](#implementing-notifications-reapop)
    *   [Getting the starter files](#starter-files)
    *   [Setting up the `NotificationsProvider` Context API](#notifications-provider-context-api)
    *   [Creating the `notification` component](#notification-component)
    *   [Setting up default notification behavior](#default-notification-behavior)
*   [Testing the React app](#testing-react-app)

## Getting started in React with the Reapop API <a name="getting-started-reapop-api">

In this article, we will learn about [Reapop](https://louisbarranqueiro.github.io/reapop/), a simple and customizable system for React. And, as mentioned above, while there are [other React notification libraries](https://blog.logrocket.com/spinners-notifications-react-app/), Reapop shines because it is easy to use, feature-packed, and customizable. Additionally, Reapop is built with [TypeScript](https://blog.logrocket.com/how-use-typescript-react-tutorial-examples/), [Redux](https://blog.logrocket.com/understanding-redux-tutorial-examples/), and [Redux thunk](https://blog.logrocket.com/async-actions-bare-redux-thunk-custom-middleware/). And, as expected, its API has built-in support for Redux. Reapop also provides Hooks and Context API if you use it without any state management. 

The Reapop API consists of six APIs. Each API exposes a collection of properties or functions for building Reapop notifications. Let’s take a look at these APIs in more detail.

### Entities

This API exposes the `Notification` object, representing a notification as the name suggests. This API contains several properties and functions, such as:

*   The `ID` of the `Notification` — if provided
*   The `Notification` title
*   The message or `Notification`
*   The status of the `Notification`
*   The position of the displayed `Notification`
*   The `onAdd` function: The method executed when the notification is displayed
*   The `onDismiss` function: The method executed right before the notification is dismissed

The complete list of the properties of the `Notification` object is seen from the object signature specified by the `Notification` interface below:

```javascript
{
    id: string
    title?: string
    message?: string
    status: Status
    position: Position
    buttons: NotificationButton[]
    image?: string
    dismissAfter?: number
    dismissible?: boolean
    onAdd?: (...args: any[]) => void
    onDismiss?: (...args: any[]) => void
    showDismissButton?: boolean
    allowHTML?: boolean
    [index: string]: any
}
```

As you can see in the code above, the `NotificationButton` is an object that represents the **button** clicked to fire a notification. It is an object with three properties: `Name`, `Primary`, and `onClick`. The `onClick` function is fired when the **`NotificationButton`** is clicked and has the following interface:

```javascript
{
    name: string
    primary?: boolean
    onClick?: (...args: any[]) => void
}
```

### Actions

This API exposes three functions, `notify`, `dismissNotification`, and `dismissNotifications`. The `notify` action is used to create or update a notification with the following signature:

```javascript
notify(notification: Partial<Notification>)
notify(message: string, options?: Partial<Notification>)
notify(message: string, status: Status, options?: Partial<Notification>)
```

The **`dismissNotification`** action is used to dismiss a notification and has the following function signature:

```javascript
dismissNotification(id: string)
```

The `dismissNofications` action is used to dismiss all notifications and has the following function signature:

```javascript
dismissNotifications()
```

### Hooks

The [Hooks API](https://blog.logrocket.com/react-reference-guide-hooks-api/) requires [React v16.8.0](https://reactjs.org/blog/2019/02/06/react-v16.8.0.html) or above and is meant to be used when you are not using another state manager. That being said, Reapop provides the `useNotification` Hook for building `Notifications` with the following syntax:

```javascript
const {notifications, notify, dismissNotification, dismissNotifications} = 
useNotifications()
```

Other Hooks provided by Reapop are the `useTheme` and the `useComponentsContext`.

### Components

This API exposes several components, including the [`NotificationSystem`](https://github.com/LouisBarranqueiro/reapop/blob/main/src/components/NotificationsSystem.tsx) component responsible for displaying notifications. A list of other components can be found [here](https://github.com/LouisBarranqueiro/reapop/tree/main/src/components).

### Helpers

This API exposes a set of helper functions. One of these functions, `setUpNotifications`, is used to define default properties, custom functions that modify notifications, and the function used to generate notification IDs. The function has the following signature:

```javascript
type NotificationConfig = {
    defaultProps: Partial<Notification>
    customizeNotification: ((notification: NewNotification) => void) | null
    generateId: ((notification: NewNotification) => string) | null
}

setUpNotifications(NotificationConfig)
```

You can set `default notifications` properties using this function, as seen below:

```javascript
import {setUpNotifications} from 'reapop'

// run this function when your application starts before creating any notifications
setUpNotifications({
    defaultProps: {
        position: 'top-right',
        dismissible: true
    } 
})
```

You can also define a custom function to modify notifications, as shown below:

```javascript
const ATopLevelComponent = () => {
    return (
        <div>
            <NotificationsSystem
                smallScreenBreakpoint={500}
                {...otherProps}
            />
        </div>
    )
}
```

In the code above, the `ATopLevelComponent` function specifies when to display notifications — at the `top-center` of the screen. This is done by customizing the `smallScreenBreakpoint` property of the `NotificationsSystem` component. The `resetNotificationsConfig` function is used to reset the values of custom notification configurations back to default.

### Themes

This API provides three built-in themes: `atalhoTheme`, `wyboTheme`, and `bootstrapTheme`. You can import and use them with the code below:

```javascript
import {atalhoTheme, wyboTheme, bootstrapTheme} from 'reapop'

const ATopLevelComponent = () => {
    return (
        <div>
            <NotificationsSystem
                theme={atalhoTheme}
                {...otherProps}
            />
        </div>
    )
}
```

## Implementing notifications with Reapop <a name="implementing-notifications-reapop">

In the previous section, we learned about Reapop’s notifications API and how to implement notifications. 

As stated before, Reapop is built with Redux, so the API works with Redux out of the box. However, it also provides API for [React Hooks](https://blog.logrocket.com/create-your-own-custom-react-hooks/) and [Context API](https://blog.logrocket.com/react-context-api-deep-dive-examples/). In this article, we will implement our notifications using the React Hooks and Context API.

### Getting the starter files <a name="starter-files">

First, clone the starter app from this [GitHub repository](https://github.com/lawrenceagles/reapop-starter), then install dependencies by running `npm install`. The starter app is a simple [Create React App](https://blog.logrocket.com/getting-started-with-create-react-app-d93147444a27/) and [Tailwind CSS](https://blog.logrocket.com/applying-dynamic-styles-tailwind-css/) application boilerplate. You can test your installation by running the dev server with `npm start`. 

If everything is successful, you should see the following: ![Notifications With Reapop in React](https://blog.logrocket.com/wp-content/uploads/2023/02/starter-app-reapop-react.png)

### Setting up the `NotificationsProvider` Context API <a name="notifications-provider-context-api">

Before working with Reapop API, install the package by running `npm i reapop`. Then, in the `index.js` file, import the `NotificationsProvider` with this line of code:

```javascript
import { NotificationsProvider } from 'reapop'
```

Now, wrap the `App` component with the `NotificationProvider` as shown below:

```javascript
...
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <NotificationsProvider>
      <App />
    </NotificationsProvider>
  </React.StrictMode>
);
...
```

This component must wrap all the components you want to access and work with notifications.

### Creating the `notification` component <a name="notification-component">

To create this custom component, create a `components` folder in the `src` folder and create two components: `Notification.js` and `NotificationButtons.js`. Then, add the following code to the `NotificationButtons.js`:

```javascript
import React from "react";
import { useNotifications } from 'reapop'
const NotificationButtons = () => {
    const { notify } = useNotifications()

    const notification1 = {
        id: '1',
        title: 'Notification 1!',
        message: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
        dismissible: true,
        dismissAfter: 3,
    }
    const notification2 = {
        id: '2',
        title: 'NOficaition 2!',
        message: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
        dismissible: true,
        dismissAfter: 2,
    }
    const notification3 = {
        id: '3',
        title: 'Notification 3!',
        message: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
        dismissible: true,
        dismissAfter: 1,
    }

    return (
        <div className="grid h-screen place-items-center">
            <div className="flex gap-x-8">
                <button
                    className="focus:outline-none text-white bg-green-700 hover:bg-green-800 focus:ring-4 focus:ring-green-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 dark:bg-green-600 dark:hover:bg-green-700 dark:focus:ring-green-800"
                    onClick={() => notify(notification1)}>
                    Alert Green!
                </button>
                <button
                    className="focus:outline-none text-white bg-red-700 hover:bg-red-800 focus:ring-4 focus:ring-red-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 dark:bg-red-600 dark:hover:bg-red-700 dark:focus:ring-red-800"
                    onClick={() => notify(notification2)}>
                    Alert Red!
                </button>

                <button
                    className="focus:outline-none text-white bg-yellow-700 hover:bg-yellow-800 focus:ring-4 focus:ring-yellow-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 dark:bg-yellow-600 dark:hover:bg-yellow-700 dark:focus:ring-yellow-800"
                    onClick={() => notify(notification3)} >
                    Alert yellow!
                </button>
            </div>
        </div>
    );
}
export default NotificationButtons;
```

We created three notification objects in the code above: `notification1`, `notification2`, and `notification3`. We also created three buttons: `Alert Green!`, `Alert Red!`, and `Alert Yellow!`. 

When clicking a **button**, we create a new notification by calling `notify`. Next, add the following code to the `Notification.js` component:

```javascript
import React, { useState, useEffect } from "react";
import NotificationsSystem, { atalhoTheme, setUpNotifications, useNotifications } from 'reapop'
import NotificationButtons from "./NotificationBottons";
const Notification = () => {
    const [transitionName, setTransitionName] = useState('Slide')
    // 1\. Retrieve the notifications to display, and the function used to dismiss a notification.
    const { notifications, dismissNotification, notify } = useNotifications()
    useEffect(() => {
        const notification = {
            id: '4',
            title: 'Alert Component Mounted!',
            message: 'You can create new notification by clicking on any of the button s below!',
            dismissible: true,
            dismissAfter: 2,
        }
        // 2\. Create a notification.
        notify(notification)
    }, [])
    return (
        <section>
            <NotificationButtons />
            <NotificationsSystem
                // 2\. Pass the notifications you want Reapop to display.
                notifications={notifications}
                // 4\. Pass a builtIn theme or a custom theme.
                theme={atalhoTheme}
                components={{
                    Transition: transitionName,
                }}
            />
        </section>
    );
}
export default Notification;
```

The code above creates a new notification once the `Notification` component mounts. This is set up in the [`useEffect`](https://blog.logrocket.com/useeffect-vs-uselayouteffect-examples/) Hook. Also, the `NotificationSystem` component is set up, and the theme is set to `altalhoTheme`.

### Setting up default notification behavior <a name="default-notification-behavior">

To set up the default notification behavior, update the `App` component as seen below:

```javascript
import React from 'react';
import { setUpNotifications } from 'reapop'
import Notification from './components/Notification';

setUpNotifications({
  defaultProps: {
    position: 'top-right',
    dismissible: true
  }
})

function App() {
  return (
    <div>
      <Notification />
    </div>
  )
}

export default App;
```

The `setUpNotifications` function is called early to set the default notification behavior in the code above. Additionally, the `notification` component is passed to the `App` component.

## Testing the React app <a name="testing-react-app">

To test the React application, start the dev server by running `npm start`. Once the server starts and the `Notification` component mounts, we get the following: ![Adding Notifications into React App With Reapop](https://blog.logrocket.com/wp-content/uploads/2023/02/notifications-reapop-react.png) Finally, we can create other notifications by clicking any of the displayed **buttons**. The created notification will be displayed like this: ![Final Product of Using Reapop to Add Notifications to React Apps](https://blog.logrocket.com/wp-content/uploads/2023/02/notifications-reapop-react-final.png)

## Conclusion

In the article, we learned about Reapop, a simple, well-thought-out React notification library built with TypeScript, Redux, and Redux thunk. 

We also learned about the Reapop notification API and built a simple React app where we implemented a notification system using Reapop’s Hooks and Context API. While we worked with the Hooks and Context API in this article, we mentioned that Reopop also provides API for [Redux](https://github.com/LouisBarranqueiro/reapop#integration--usage). 

After going through this article, I hope you have learned enough to start implementing notifications with Reapop in your next React project.

---
## Cut through the noise of traditional React error reporting with LogRocket

[LogRocket](https://lp.logrocket.com/blg/react-signup-issue-free) is a React analytics solution that shields you from the hundreds of false-positive errors alerts to just a few truly important items. LogRocket tells you the most impactful bugs and UX issues actually impacting users in your React applications.

[![LogRocket signup](https://blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png)](https://lp.logrocket.com/blg/react-signup-general)

[LogRocket](https://lp.logrocket.com/blg/react-signup-issue-free) automatically aggregates client side errors, React error boundaries, Redux state, slow component load times, JS exceptions, frontend performance metrics, and user interactions. Then LogRocket uses machine learning to notify you of the most impactful problems affecting the most users and provides the context you need to fix it.

Focus on the React bugs that matter — [try LogRocket today](https://lp.logrocket.com/blg/react-signup-issue-free).