How to setup React global alert popup in 10mins
Tags: react, javascript, webdev
Published: 2022-03-20 07:09:42

It's annoying to add alert popup in every component after an action. A global alert popup not only make your life easier, but also improves user experience. A nice alert popup give users a clear feedback as a result of their actions and any server reponse. 

Here's how you can set up global alert popup in React in 10 minutes using context hook.

## Create AlertContext

Our alert context has two states: `text` and `type`. `text` is the displayed message on the alert, and `type` is the "severity" of the alert (success / info / warning / error).

The context has one action: `setAlert()`. It takes in text and type as parameters and set them to the state. After a set time period, the state will be set back to empty.

```javascript
// AuthContext.js
import { createContext, useState } from 'react';

const ALERT_TIME = 5000;
const initialState = {
  text: '',
  type: '',
};

const AlertContext = createContext({
  ...initialState,
  setAlert: () => {},
});

export const AlertProvider = ({ children }) => {
  const [text, setText] = useState('');
  const [type, setType] = useState('');

  const setAlert = (text, type) => {
    setText(text);
    setType(type);

    setTimeout(() => {
      setText('');
      setType('');
    }, ALERT_TIME);
  };

  return (
    <AlertContext.Provider
      value={{
        text,
        type,
        setAlert,
      }}
    >
      {children}
    </AlertContext.Provider>
  );
};

export default AlertContext;

```
Don't forget to wrap the context provider around your app components.

```javascript
// index.js
ReactDOM.render(
  <AlertProvider>
   <App />
  </AlertProvider>,
  document.getElementById('root')
);
```
## Custom useAlert hook

Create a custom useAlert hook to access state and actions in AlertContext.

```javascript
// useAlert.js
import { useContext } from 'react';
import AlertContext from '../contexts/AlertContext';

const useAlert = () => useContext(AlertContext);

export default useAlert;
```

## Popup Component

Next, we create a popup component that displays the alert with text and type from useAlert. The popup will appear once setAlert passes text and type to AlertContext, and will disappear after the set time period. 

I use [Alert](https://mui.com/material-ui/react-alert) from MaterialUI to make it look nicer.

```javascript
// AlertPopup.js
import { Alert } from '@mui/material';
import useAlert from '../../hooks/useAlert';

const AlertPopup = () => {
  const { text, type } = useAlert();

  if (text && type) {
    return (
      <Alert
        severity={type}
        sx={{
          position: 'absolute',
          zIndex: 10,
        }}
      >
        {text}
      </Alert>
    );
  } else {
    return <></>;
  }
};

export default AlertPopup;
```
Put AlertPopup on top of your app components so it's visible anywhere.

```javascript
//route.js
const routes = [
  {
    path: '/',
    element: (
      <AlertPopup />
      <Dashboard />
    ),
    children: [ ... ]
  }
]
```

## Use it in your components

Call setAlert on action feedbacks in your components to show the alert popup.

```javascript
const { setAlert } = useAlert();
...
<Button onClick={setAlert('Edit success!', 'success')}>
  Edit
</Button>
```

![Success Alert](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l3lcn0e3jn3ea4pz7grl.png)

It's always nice to use alert to show server response to the user.

```javascript
try {
  const res = await axios.post('api/user/login');
  setAlert('Login success!', 'success');
} catch(err) {
  setAlert(err.message, 'error');
}
```