Editor’s note: This article was last updated for code clarity on 25 October 2023.
When users interact with a UI, certain operations occur behind the scenes. These operations may succeed, fail, or time out. Therefore, it is important to provide feedback in a way that does not interfere with the user’s experience.
A toast is a UI that unobtrusively provides feedback about an operation using a popup. Unlike similar UIs, a toast usually disappears after a given time. Therefore, removing it doesn’t require user action. 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.
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.
Toasts or toast notifications are pop-up messages that provide feedback to the user. This feedback could be a success, warning, or error message, as shown in the image below:
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: toast.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: toast.POSITION.TOP_RIGHT, }); toast.success("Success Notification !", { position: toast.POSITION.TOP_CENTER, }); toast.success("Success Notification !", { position: toast.POSITION.TOP_LEFT, }); toast.success("Success Notification !", { position: toast.POSITION.BOTTOM_RIGHT, }); toast.success("Success Notification !", { position: toast.POSITION.BOTTOM_LEFT, }); toast.success("Success Notification !", { position: toast.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: toast.POSITION.TOP_RIGHT, }); toast.error("Error Notification !", { position: toast.POSITION.TOP_CENTER, }); toast.warning("Warning Notification !", { position: toast.POSITION.TOP_LEFT, }); toast.info("Information Notification !", { position: toast.POSITION.BOTTOM_CENTER, }); toast("Default Notification !", { position: toast.POSITION.BOTTOM_LEFT, }); toast("Custom Style Notification with css class!", { position: toast.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 toasts in React-Toastify.
A custom toast is a notification to which you can apply your own custom style. This allows you to give 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: toast.POSITION.BOTTOM_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 afterwards:
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
, and so on — 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
. Let’s go over a few of these:
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
function 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 me explain 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 saw 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 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.
Thanks for reading. I hope this article was helpful in demonstrating how to use React-Toastify. If you have any other questions, let me know in the comment section below.
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>
Would you be interested in joining LogRocket's developer community?
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 nowLearn 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.
Handle frontend data discrepancies with eventual consistency using WebSockets, Docker Compose, and practical code examples.
Efficient initializing is crucial to smooth-running websites. One way to optimize that process is through lazy initialization in Rust 1.80.