An alert message is a built-in component of the web that is commonly used in online applications to display status messages like warnings, errors, success messages, information, and confirmation consents.
In this tutorial, we’ll review a few popular frameworks for creating alert messages in React, then we’ll create our own custom alert message with complex styling and additional features. The full code for this tutorial is available at the GitHub repository. Let’s get started!
Before we build our custom alert message, let’s first grasp what an alert message component looks like.
An alert message should dynamically display a message to the user. It should also have a close button with an event handler to hide the component and dynamic styling for different messages.
We’ll create a custom alert message with the following features:
Type
: The type of message to be displayed, i.e., error, success, primary, or secondary. Type also determines the style applied to the alert message elementMessage
: A text message to explain the error or warning to the userChildren
: The elements containing the content to be displayedHandleClose
: A function fired when the component requests to be closedThe React community provides a wide variety of alert frameworks that you can use in your projects to streamline the development process. Before we build our custom alert message component, let’s take a look at a few of these frameworks.
React-Toastify is a lightweight package based on Toastify that lets you add personalized alerts to your React project. You can add an alert message to your React component using React-Toastify with the code snippet below:
import React from 'react'; import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; function App(){ const notify = () => toast("Wow so easy!"); return ( <div> <button onClick={notify}>Notify!</button> <ToastContainer /> </div> ); }
rc-notification is another React UI component library that allows you to add an alert message to your React project. The code snippet below shows an alert message using rc-notification.
Import Notification
from rc-notification:
Notification.newInstance({}, notification => { notification.notice({ content: 'content' }); });
Alert
The Chakra UI Alert
component provides simple, modular, accessible, reusable, and composable React components that make it super easy to create and customize alert messages in your React application.
The code snippet below is an example of an alert message using @chakra-ui/alert
:
<Alert status='error'> <AlertIcon /> <AlertTitle mr={2}>Your browser is outdated!</AlertTitle> <AlertDescription>Your Chakra experience may be degraded.</AlertDescription> <CloseButton position='absolute' right='8px' top='8px' /> </Alert>
There are a bunch of other React alert message frameworks that you can check out. Instead of using these frameworks, we’ll create our own custom alert message. Let’s get started!
Create a React project for the demonstration in this tutorial with the command below:
npx create-react-app custom-alert
Once the installations in the above command are completed, move into the project directory with the command below:
cd custom-alert
Then, start the server with the command below:
npm start
With our React project set up, let’s create the alert component. Create a component/Alert.jxs
folder in the src
directory and add the following code snippets:
export default function Alert() { return ( <div> <span> ×</span> message </div> ); }
In the code snippet above, we created an alert component. The command doesn’t do much yet; let’s give it a better look by adding some styling.
To add styling, first, create a style.module.css
file in the src/components
folder and add the following CSS styles:
/* The alert message box */ .alert { position: relative; padding: 1rem 1rem; margin-bottom: 1rem; border: 1px solid transparent; border-radius: 0.25rem; } .error { color: #842029; background-color: #f8d7da; border-color: #f5c2c7; } .success { color: #0f5132; background-color: #d1e7dd; border-color: #badbcc; } .warning { color: #664d03; background-color: #fff3cd; border-color: #ffecb5; } .primary { color: #084298; background-color: #cfe2ff; border-color: #b6d4fe; } .secondary { color: #41464b; background-color: #e2e3e5; border-color: #d3d6d8; } .info { color: #055160; background-color: #cff4fc; border-color: #b6effb; } /* The close button */ .closebtn { margin-left: 15px; color: white; font-weight: bold; float: right; font-size: 22px; line-height: 20px; cursor: pointer; transition: 0.3s; } /* When moving the mouse over the close button */ .closebtn:hover { color: black; } .hide { display: none; }
In the stylesheet above, we defined some CSS styles for each type of message we’ll render to the users.
Modify the Alert.jsx
file to use the styles we’ve defined above. We’re applying the styles dynamically based on the type of style the user chooses and applying more than one style to elements in our alert component, so we’ll need to install a module called classnames with the command below:
npm install classnames
Once the module is installed, modify the Alert
component to look like the code snippet below:
import style from "./style.module.css"; import css from "classnames"; import React from "react"; export default function Alert({ children, type, message }) { const renderElAlert = function () { return React.cloneElement(children); }; return ( <div className={css(style.alert, style[type])}> <span className={style.closebtn}> × </span> {children ? renderElAlert() : message} </div> ); }
In the code snippet above, we import the style
and the classnames modules we just installed.
We get the children
, type
, and message
props from the component. Then, we create a renderElAlert
that will render any child element used to add a message using the React.cloneElement
function. We check if the user’s message is in an HTML element and render the children
prop, otherwise, we display the message
prop.
We need to give the user the freedom to close the message when they are done reading the content.
We’ll add an event listener to the component and listen to the event with the click of the close button. When the user clicks the close button, we’ll modify the state of the component and add the hide
attribute to the className
property.
Your Alert
component should look like the code below:
import style from "./style.module.css"; import css from "classnames"; import React from "react"; import { useState } from "react"; export default function Alert({ children, type, message }) { const [isShow, setIsShow] = useState(true); const renderElAlert = function () { return React.cloneElement(children); }; const handleClose = (e) => { e.preventDefault(); setIsShow(false); }; return ( <div className={css(style.alert, style[type], !isShow && style.hide)}> <span className={style.closebtn} onClick={handleClose}> × </span> {children ? renderElAlert() : message} </div> ); }
Alert
componentAt this point, we’ve successfully created our first custom React alert. Open the App.js
file and test the component with the code snippet below:
import Alert from "./components/Alert"; function App() { return ( <div className="App"> <Alert type="error" message="Error" /> <Alert type="success"> <p>Success message</p> </Alert> <Alert type="primary"> <h4>primary message</h4> </Alert> <Alert type="secondary"> <span>secondary message</span> </Alert> </div> ); } export default App;
In the code snippet above, we imported our Alert
component and created some alert messages. Notice how we supplied a message without wrapping it around an element in the initial alert message. The remainder of the code was then wrapped around other HTML elements. You should see the alerts displayed on the screen as shown in the screenshot below:
In this tutorial, we reviewed the necessary features for an alert message, explored a few popular libraries for building alert messages, and finally built our own custom version from scratch.
Feel free to clone or fork the GitHub repository for this tutorial and add more features to it. Perhaps you can drop your questions or suggestions in the comment section or reach out to me on Twitter. Happy coding!
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowCompare Prisma and Drizzle ORMs to learn their differences, strengths, and weaknesses for data access and migrations.
It’s easy for devs to default to JavaScript to fix every problem. Let’s use the RoLP to find simpler alternatives with HTML and CSS.
Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.