Editor’s note: This article was last reviewed and updated on 19 November 2024.
Toast messages, or toast notifications, are unobtrusive, in-app pop-up messages that provide users feedback about an operation. Toasts usually disappear after a given time; therefore, removing them doesn’t require any user action. However, you can also close a toast notification before the expiration of the timeout.
The styling and positioning of a toast largely depend on the purpose and nature of the user feedback. For example, a notification that indicates success is styled differently from a warning or an error notification.
The feedback that toast notifications provide can be messages of success, warning, or error, as shown in the image below:
There are several toast libraries in the React ecosystem. In this article, we will explore how to use React-Toastify in a React project. To follow along, you need to install the Node runtime environment and create a React project. We will go over how to install React-Toastify in the next section.
React-Toastify is a free, popular, and MIT-licensed package that you can use to add toast notifications to your React application. There are several other similar toast libraries in the React ecosystem.
Use any of the commands below to install React-Toastify in a React project:
# npm npm install react-toastify # yarn yarn add react-toastify
After installation, import the ToastContainer
component and the toast
object as shown in the example below. React-Toastify also has a CSS file that you must import:
import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css';
In this section, you will learn how to use React-Toastify to style toast messages. If you haven’t, start by creating a React app.
As toast messages are notifications you can use to provide feedback to the user, they can be displayed on user login success, login error, or when a network request succeeds, fails, or times out.
In your App.js
file, import react-toastify
and its CSS file and invoke the toast.success
function with the notification message like so:
import React from "react"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; function App() { const showToastMessage = () => { toast.success("Success Notification !", { position: "top-right" }); }; return ( <div> <button onClick={showToastMessage}>Notify</button> <ToastContainer /> </div> ); } export default App;
Notice we also rendered the ToastContainer
in the code above. This container wraps our toast pop-ups. Without it, the toast pop-ups won’t be displayed.
When you click the Notify
button, the code above will display a toast similar to what you see below:
By default, all toasts are positioned at the top right of the page. This position can be changed by assigning a new position to the toast. React-Toastify allows for six positions:
Depending on where you want the toast message, you can set its position like so:
toast.success("Success Notification !", { position: "top-right", }); toast.success("Success Notification !", { position: "top-center", }); toast.success("Success Notification !", { position: "top-left", }); toast.success("Success Notification !", { position: "bottom-right", }); toast.success("Success Notification !", { position: "bottom-left", }); toast.success("Success Notification !", { position: "bottom-center", });
The image below shows a toast message in all of the six possible locations on the webpage:
Similarly to setting your toast message’s position, you can use React-Toastify to specify different types of toast messages to better understand the information displayed and improve user experience.
This technique uses different styling for each message type to make it easier to quickly understand the information and its intent. For example, a red-colored toast UI typically implies a warning or error message, just as a green-colored message typically implies a successful response.
You can use specific toast functions for the different toast message variants. Add the following changes in the click event handler in your App.js
file:
toast.success("Success Notification !", { position: "top-right", }); toast.error("Error Notification !", { position: "top-center", }); toast.warning("Warning Notification !", { position: "top-left", }); toast.info("Information Notification !", { position: "bottom-center", }); toast("Default Notification !", { position: "bottom-left", }); toast("Custom Style Notification with css class!", { position: "bottom-right", className: "foo-bar", });
The code above should display the toast messages below:
The last toast notification at the bottom right of the image above is a custom toast. Unlike the others, we added a className
to it. Let’s learn more about custom toast messages in React-Toastify.
A custom toast allows you to implement the toast UI styling that matches your brand color, website, or application theme.
To style your toast message, first assign it a className
as in the example below:
toast("This is a custom toast Notification!", { position: "top-left", className: "toast-message", });
Next, use the className
selector to apply the styles in your CSS file:
.toast-message { background: darkblue; color: #fff; font-size: 20px; width: 34vw; padding: 30px 20px; }
With the styles specified in the example above, you should see the following result:
Promise
-based toasts in React-ToastifyIn addition to the toast variants highlighted above, you can also use React-Toastify to create and display Promise
-based notifications. You can perform asynchronous operations such as network requests and use these toast notifications to display a success or error message when the operation is complete.
To create Promise
-based toasts, add the following to your App.js
file:
useEffect(() => { const myPromise = new Promise((resolve) => fetch("https://jsonplaceholder.typicode.com/posts/1") .then((response) => response.json()) .then((json) => setTimeout(() => resolve(json), 3000)) ); toast.promise(myPromise, { pending: "Promise is pending", success: "Promise Loaded", error: "error", }); }, []);
In the toast.promise
function call, we set the pending
, success
, and error
messages. The pending
message will display as the fetch executes. Depending on the outcome, either the success
or error
message will display afterward:
You can also add a custom icon to your toast notification depending on the type. To add a custom icon, let’s look at the code below:
const CustomIcon = ({ isLoading, type }) => { if (isLoading) return <Spinner />; switch (type) { case "success": return <span>✅</span>; case "error": return <span>❌</span>; case "warning": return <span>⚠️</span>; case "info": return <span>ℹ️</span>; default: return <span></span>; } };
The function above accepts three props: theme
, isLoading
, and type
. With these props, we can assign different icons to our toast
types. We can also change the icon color if you see fit. isLoading
checks if toast.promise
is true and active.
Finally, pass the CustomIcon
function to the icon
props in ToastContainer
:
<ToastContainer icon={CustomIcon} />
As you can see from our previous sections and examples, the toast
notifications are displayed vertically when a new toast notification is active. We can make them overlap or stacked instead for a better user experience. This way, the notifications won’t take up much space on our viewport.
To do this, add the stacked
prop to the ToastContainer
:
<ToastContainer stacked hideProgressBar icon={CustomIcon} position="bottom-right" style={{ width: "20vw" }} />
I added the hideProgressBar
prop so that the toasts look better and less chaotic when they are stacked:
useNotificationCenter
Hook in React-Toastify v9The useNotificationCenter
Hook is a React-Toastify addon introduced in React-Toastify v9. You can use it to build a notification center on top of React-Toastify.
Whenever you invoke any toast variant function — like toast.update
, toast.promise
, toast.info
, etc. — while using the useNotificationCenter
Hook, the toast notification will get added to the toast center.
Before using this Hook, first, import it from react-toastify
addons. You can use it in your component like any other React Hook:
import { useNotificationCenter } from "react-toastify/addons/use-notification-center"; const App = () => { const { notifications } = useNotificationCenter(); return null; };
The useNotificationCenter
Hook returns several methods and properties. Some of these methods include notifications
, clear
, markAllAsRead
, markAsRead
:
notifications
gives us access to all the notification items or toast messages that we have in our center. Each notificationItem
in the notifications
array contains data such as the id
, read
status (Boolean), theme
, isLoading
status (Boolean), etc.clear
removes all the notifications from the notification centermarkAllAsRead
marks all the notifications as read. It changes the value of the read
Boolean property of every notificationItem
from false
to true
. In comparison, markAsRead
only changes the read
Boolean property of one notificationItem
to true
Now that we understand the useNotificationCenter
Hook along with toast message positions, types, and customization, let’s see how we can use them together in an application.
First, destructure the methods returned by the useNotificationCenter
Hook we went over in the previous section in your App.js
file:
import React from 'react'; import { useNotificationCenter } from 'react-toastify/addons/use-notification-center'; import { toast, ToastContainer } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; const App = () => { const { notifications, clear, markAllAsRead, markAsRead } = useNotificationCenter(); }
In the example above, we also imported toast
and ToastContainer
with its CSS file. Let’s declare an event handler that will create a toast when a button is clicked:
import React from "react"; import { useNotificationCenter } from "react-toastify/addons/use-notification-center"; import { toast, ToastContainer } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; const App = () => { const { notifications, clear, markAllAsRead, markAsRead } = useNotificationCenter(); const showToast = () => { toast("Hello World", { data: { title: "Hello World Again", text: "We are here again with another article", }, }); }; return ( <div> <p>{notifications.length}</p> <button onClick={showToast}>Click me</button> <ToastContainer /> </div> ); }; export default App;
In the code above, we added a paragraph tag to display the number of toast messages added to the notification center.
Clicking the button will create a new toast and the paragraph text will display the number of toast messages we’ve created:
Cool, right? Let’s see what else we can do. As mentioned earlier, you can perform sorting, mapping, and other actions on the notifications
array returned by the useNotificationCenter
Hook.
Copy and paste the code below into the the App.js
file:
import React from "react"; import { useNotificationCenter } from "react-toastify/addons/use-notification-center"; import { toast, ToastContainer } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; const App = () => { const { notifications, clear, markAllAsRead, markAsRead } = useNotificationCenter(); const showToast = () => { toast("Hello World", { data: { title: "Hello World Again", text: "We are here again with another article", }, }); }; const showSuccessToast = () => { toast.success("Hello World", { data: { title: "Success toast", text: "This is a success message", }, }); }; const showErrorToast = () => { toast.error("Hello World", { data: { title: "Error toast", text: "This is an error message", }, }); }; return ( <div> <p>{notifications.length}</p> <button onClick={showToast}>Default</button> <button onClick={showSuccessToast}>Success</button> <button onClick={showErrorToast}>Error</button> <br /> <br /> <button onClick={clear}>Clear Notifications</button> <button onClick={() => markAllAsRead()}>Mark all as read</button> <ul> {notifications.map((notification) => ( <li onClick={() => markAsRead(notification.id)} key={notification.id} style={ notification.read ? { background: "green", color: "silver", padding: "0 20px" } : { border: "1px solid black", background: "navy", color: "#fff", marginBottom: 20, cursor: "pointer", padding: "0 20px", } } > <span>id: {notification.id}</span> <p>title: {notification.data.title}</p> <p>text: {notification.data.text}</p> </li> ))} </ul> <ToastContainer /> </div> ); }; export default App;
Let’s break down the code above.
First, we are mapping through the notifications
array, which is an array of notification items, and getting the id
, title
, and text
of our toast messages.
Then, we register onClick
event handlers on the notification items. When a notification item gets clicked, we use the markAsRead
function to mark the item as read. We also change the background color of a notification item to differentiate between read and unread notifications.
The “Mark all as read” button uses the markAllAsRead
function to change the read
status of all notification items to true
. When this button is clicked, all item backgrounds will change color.
Lastly, the “Clear Notifications” button uses the clear
function to delete or remove all items from the notification center.
Remember, when you invoke any toast variant method — whether toast.success
, toast.error
, toast.update
, or any other type — the toast will be added to the notification center, like so:
In this tutorial, we learned how to style toast messages using React-Toastify. We also explored how to style custom toast notifications to suit our preferences. Finally, we explored how to use the useNotificationCenter
Hook to create a cool notification center where we can display all our toast notifications.
React-Toastify is a useful React toast library because it is highly customizable and provides many toast variants. Other tools are available if you need even more functionality, such as implementing animated toasts in React.
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 nowBuild scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.
Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]