Painless alert management in React

react material ui alerts example with state management

Managing alerts in React can be effortless when the right technologies are utilized. Selecting Eventrix and MUI is a good example. Thanks to using them, alerts can be managed effortlessly.

MUI gives the developer an opportunity to display well designed alert messages. When using Eventrix, developers can communicate between a component using the MUI alerts component and the place where they want to call an alert. Take a look at an example below of how to use Eventrix with MUI.

Eventrix with MUI

import { useEvent } from "eventrix";
import { useState } from "react";
import Stack from "@mui/material/Stack";
import Alert from "@mui/material/Alert";

const Alerts = () => {
    const [alerts, setAlerts] = useState([]);
    useEvent("Alerts:show.success", (message) => {
        const id = new Date().getTime();
        setAlerts([{ message, type: 'success', id }, ...alerts]);
    });
    
    return (
        <Stack spacing={2}>
            {alerts.map(({ message, type, id }) => (
                <Alert key={id} severity={type}>{message}</Alert>
            ))}
        </Stack>
    );
}

export default Alerts;
vie

 

This example shows how to listen to success messages.

import React from "react";
import { useEmit } from "eventrix";
import Button from "@mui/material/Button";

const AlertButton = () => {
    const emit = useEmit();
    return (
        <Button
            variant="contained"
            onClick={() => {
                emit("Alerts:show.success", "Success message");
            }}
        >
            Show success alert
        </Button>
    )
}

export default AlertButton;

 

Here is an example of how to display alerts from any place of the application.

You can see the full implementation here. The example contains all kind of messages and alert auto removal functionality.

Conclusion

Usually developers need to display alerts in many different places of an application and they don’t want to use the same code repeatedly. Instead, Eventrix could be applied to communicate with alert components that display the alert message. Thanks to that you can write less code, and achieve the same result. On top of that, this functionality can be reusable in other places.