Frontend developers use HTML, CSS, and JavaScript to build graphical interfaces for websites that users can see and interact with. The objective is to build and design a site users can open, use, and interact with easily, especially when reading vital information.
Part of frontend development involves how beautiful and aesthetically pleasing the website is, also known as UI. Another aspect called UX involves how easy and straightforward it is to use the website.
Different tools exist to help us to achieve both great UI and UX. One of the cool tools we can use in the frontend is React-Toastify.
In this article, we will learn about React-Toastify and how we can use it to create notifications, messages, and pop-ups in our React apps. We will cover:
- What is React-Toastify?
- Styling your toast messages with React-Toastify
- Putting all your React-Toastify knowledge together
To follow along with this tutorial, you need React and Node installed in your computer. We will go over how to install the React-Toastify package in the next section.
What is React-Toastify?
React-Toastify is one of the top React toast libraries available. This tool allows you to add toast notifications to your application with ease and can also be used to set notifications and alerts.
What is a toast notification?
Toast or Toastify notifications are pop-up messages that display some information to the user. This information could be a success message, warning, error, and so on, as shown in the image below:
Use any of the commands below to install the React-Toastify package.
/* NPM */ $ npm install --save react-toastify /* YARN */ $ yarn add react-toastify
Once installation is done, you must then import the package inside your component as demonstrated below. React-Toastify comes with a CSS file that must be imported for the tool to work.
import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css';
Styling your toast messages with React-Toastify
Let us spin up our React app and see how we can use the React-Toastify to style our toast messages.
Remember, toast messages are notifications or alerts that we want to show the user at a given time. These messages could be shown on user login success, on login error, when a bad request occurs, when vital information is clicked, and so on.
In your App.js
file, import the react-toastify
package and its CSS file:
import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css';
After that, you can call the toast
and insert your Success Notification !
message:
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 called the ToastContainer
in the code above. This container houses our toast pop-ups. Without it, our toast pop-ups won’t be displayed.
Rendering this code will give us the below result when we click on the Notify
button:
How to change your toast message’s position
All toasts are positioned at the top right of your browser by default. This position can be changed by assigning a new position to the toast. React-Toastify allows for six positions:
- Top right
- Top center
- Top left
- Bottom right
- Bottom center
- Bottom left
Depending on where you want your toast message, you can set a position like so in your App.js
file:
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 });
How to differentiate between toast message types
Similarly to setting your toast message’s position, you can have your toast emitter specify different types of toast messages so users can better understand the information being displayed.
Specification is one helpful way to improve the user experience for your React app. This technique uses different colors for each toast message type to make it easier for users to quickly understand the information they see.
For example, a red-colored toast message typically implies a warning or error message, just as a green-colored message typically implies a successful response. In essence, you can specifically set a toast variant for error messages, general information, warnings and so on.
To specify your toast emitter, call your toast in your App.js
file with any of the below variants:
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' });
Doing this will easily tell the user what is being displayed.
Observe the last toast notification we created, shown at the bottom right of the image above. We can see that we added a className
to it, unlike the others. That is a custom toast. Let’s learn more about custom toasts in React-Toastify.
How to style a custom toast message
A custom toast is a notification we can style according to our preferred styling. This allows us to give our toast message our preferred height, font, font size, background, and so much more depending on the kind of message we want to display.
For example, we might want to display a toast that matches our website or application styling. A custom toast allows us to do so.
To style your own toast message in your App.js
file, first give it a className
as demonstrated below:
toast('This is a custom toast Notification!', { position: toast.POSITION.BOTTOM_LEFT, className: 'toast-message' });
Next, style it in your CSS file using the className
according to your preferences:
.toast-message { background: darkblue; color: #fff; font-size: 20px; width: 34vw; padding: 30px 20px; }
With the styles specified in the code block example above, you should see the following result:
How to create promise toasts in React-Toastify
In addition to these toast variants, React-Toastify also allows us to create and display Promise
notifications. These toast notifications show up when any API call is being processed and returns either a success or an error toast message after the call is complete.
To create promise toasts, add the following to your App.js
file:
const myPromise = new Promise((resolve) => fetch("https://jsonplaceholder.typicode.com/post") .then((response) => response.json()) .then((json) => setTimeout(() => resolve(json), 3000)) ); useEffect(() => { toast.promise(myPromise, { pending: "Promise is pending", success: "Promise Loaded", error: "error" }); }, []);
In toast.promise
, we set 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.
Understanding the useNotificationCenter
update in React-Toastify v9
useNotificationCenter
is a new and major update that came with the release of React-Toastify v9. It is a hook that builds your notification center on top of React-Toastify.
Whenever you call any toast variant — like toast.update
, toast.promise
, toast.info
, and so on — the toast notification will get added to the toast center.
The useNotificationCenter
is an array that contains all notifications and therefore allows us perform some array functions like filtering, sorting, mapping, etc on it. Let’s use an example to understand this hook better.
Before using this hook, first import it from react-toastify addons
, and then call it before the return
statement in your App.js
file:
import { useNotificationCenter } from 'react-toastify/addons/use-notification-center'; const App = () => { const { notifications } = useNotificationCenter(); return ()}
The useNotificationCenter
hook allows us to use a number of functions and values, including notifications
, clear
, markAllAsRead
, markAsRead
, and many others. Let’s go over what a few of these mean.
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 its id
, read
status (boolean), theme
, isLoading
status (boolean), and other information.
The clear
function removes all the notifications from the notification center.
markAllAsRead
marks all the notifications as read, which means it changes the read
boolean of every notificationItem
from false
to true
. In comparison, markAsRead
only changes one notificationItem
boolean to true
.
Putting all your React-Toastify knowledge together
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 our application.
First, import the four useNotificationCenter
functions we went over in the previous section into 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(); }
As seen above, we also imported our toast
and ToastContainer
with its CSS file so we can call our toast. Continuing in the App.js
file, let’s create a function to call our toast message:
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;
Notice that in the code above, we added a paragraph tag to show the number of toast messages we have called or added to our notification center.
When we click our button to call our toast, it automatically enters the notification center. The number above the button will then update to show how many toast message we’ve added, like so:
Cool, right? Let’s see what else we can do with the hook. As mentioned earlier, the useNotificationCenter
hook allows us to perform sorting, mapping, and other actions on the notifications
array.
Still inside your App.js
file, copy and paste the code below:
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 Dash = () => { 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 Dash;
Let me explain the code above.
First, we are mapping through our notification center (which is an array of notification items) and getting the id
, title
, and text
of our toast messages.
Then, thanks to the React onClick
event handler, when any notification item gets clicked, we can use the markAsRead
function to mark the item as read.
We also instructed the program to change the background color from blue to green on read
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, any toast variant you call — whether toast.success
, toast.error
, toast.update
, or any other type — will be added to the notification center, like so:
Conclusion
In this tutorial, we learned how to style our toast messages using React-Toastify. We also saw that we can create and style our custom toast notifications any way we want to.
Lastly, we saw how to use the useNotificationCenter
hook to create a cool notification center and 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 the React-Toastify tool properly. If you have any other questions, let me know in the comment section below.
Get setup with LogRocket's modern React error tracking in minutes:
- Visit https://logrocket.com/signup/ to get an app ID.
- Install LogRocket via NPM or script tag.
LogRocket.init()
must be called client-side, not server-side. - (Optional) Install plugins for deeper integrations with your stack:
- Redux middleware
- ngrx middleware
- Vuex plugin
$ 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>