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.
// 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.
// 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.
// 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 from MaterialUI to make it look nicer.
// 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.
//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.
const { setAlert } = useAlert();
...
<Button onClick={setAlert('Edit success!', 'success')}>
Edit
</Button>
It's always nice to use alert to show server response to the user.
try {
const res = await axios.post('api/user/login');
setAlert('Login success!', 'success');
} catch(err) {
setAlert(err.message, 'error');
}
Top comments (0)