A feedback mechanism that is both timely and unobtrusive has been essential in improving user experience in modern web development. Brief message display devices that can simply show and disappear, independent of any user action, such as toast notifications, serve this well. React-Toastify is a very good library that enables the easy implementation and styling of toast messages within a React application. The article discusses the latest features of React-Toastify, including the new features available, and also takes you through styling toast messages to your specific application’s design.
What is React-Toastify?
React-Toastify is a React library where developers can create toast notifications in their applications. This is accomplished by setting parameters to adjust the toasts positioning, style, and behavior for an individualized experience. The library supports types of success, error, warning, and info that notify different meanings.
Key Features of React-Toastify
- Simplicity: Getting React-Toastify into a React project with little setting up is very uncomplicated.
- Customization: The developer is free to customize the appearances and behaviors of toast for position, duration, style, etc.
- Accessibility: It was designed to take place in the library as accessible notifications.
- Promise-Based Notifications: It also allows promise-based toasts, which is useful for asynchronous work.
- Notification Center: Version 9 includes the
useNotificationCenter
hook, which allows developers to create notification centers in applications.
Understanding the use of React-Toastify
Installing React-Toastify
To start the React-Toastify, you can install it through npm or yarn:
npm install react-toastify
# or
yarn add react-toastify
After installation, import the necessary components and CSS in the main application file:
import React from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
Display a Basic Toast Notification
For displaying a toast notification, the toast
function will suffice, which is included in React-Toastify. It is required to plug in ToastContainer
component into your component tree, as it will render the toasts:
function App() {
const notify = () => {
toast('This is a default notification!');
};
return (
<div>
<button onClick={notify}>Show Notification</button>
<ToastContainer />
</div>
);
}
export default App;
Positioning Toast Messages
By default, toasts are at the top right corner of the page. You can change this in React Toastify by specifying the position
property. The available positions are:
toast.POSITION.TOP_RIGHT
toast.POSITION.TOP_CENTER
toast.POSITION.TOP_LEFT
toast.POSITION.BOTTOM_RIGHT
toast.POSITION.BOTTOM_CENTER
toast.POSITION.BOTTOM_LEFT
To set a toast’s position:
toast('This is a top-center notification!', {
position: toast.POSITION.TOP_CENTER,
});
Differentiating between Toast Message Types
React-Toastify defines methods for displaying all types of notifications. Each link takes on a different style based on what the message is about:
toast.success('Success message')
toast.error('Error message')
toast.warning('Warning message')
toast.info('Information message')
For example:
toast.success('Operation successful!', {
position: toast.POSITION.BOTTOM_RIGHT,
});
Styling Custom Toast Messages
Let’s make toast notifications go with your application design by custom styling CSS classes. First, assign a className
to the toast and define the respective styles:
toast('This is a custom-styled toast!', {
className: 'custom-toast',
});
In your CSS file:
.custom-toast {
background-color: #333;
color: #fff;
font-size: 16px;
padding: 15px;
}
Creating Promise-Based Toasts
React-Toastify toast.promise
method shows toast messages according to a promise’s state, such as pending, success, error, etc., for an asynchronous promise:
const myPromise = fetchData();
toast.promise(myPromise, {
pending: 'Loading...',
success: 'Data loaded successfully!',
error: 'Error loading data',
});
Adding Custom Icons to Toast Notifications
You can make your toast messages really great with custom icons. Just pass a React component as the icon
property:
import { FaCheckCircle } from 'react-icons/fa';
toast.success('Operation successful!', {
icon: ,
});
Stacked Toast Notifications
Toastify provides the following capability to show multiple toasts simultaneously. By default, each new toast will be stacked as if on top of the existing one. However, you can control this opportunity through the newestOnTop property in ToastContainer
:
<ToastContainer newestOnTop={false} />
Notification Center with useNotificationCenter
Hook
Version 9 of React-Toastify brought the useNotificationCenter
hook for making a notification center in the application. With this hook, you can gain access to notifications and methods to deal with them.
import { useNotificationCenter } from 'react-toastify/addons/use-notification-center';
const { notifications, clear, markAllAsRead } = useNotificationCenter();
You can then render a list of notifications and provide functionality to mark all as read or clear all notifications.
React Toastify Props Overview
Concerning your toast notifications, React-Toastify also provides several props to <ToastContainer />
and the toast
function.
ToastContainer Props
position
: Default position for toast (e.g.,toast.POSITION.TOP_RIGHT
).autoClose
: Time after which, in milliseconds, a toast will be closed automatically. Set tofalse
to turn off auto-close.hideProgressBar
: Boolean to hide/display a progress bar.pauseOnHover
: Pause auto-close if the user hovers on toast.newestOnTop
: True or false- depending on whether or not the most recent toast appears on top of the pile.
Toast Props
className
: Custom CSS class to style the toast.icon
: Custom icons allowed for particular toasts.closeOnClick
: Toast being clickable to dismiss.
Handling Toast Lifecycle with Callbacks
React-Toastify allows callbacks for toast lifecycle to keep track of events like when a toast is shown or toasted. The callbacks onOpen
and onClose
are defined to trigger actions associated with opening or closing a toast.
toast.success('Toast with callbacks!', {
onOpen: () => console.log('Toast is opened'),
onClose: () => console.log('Toast is closed'),
});
Animations and Transitions
You can also define your own entry and exit animations for toasts using the transition prop. React-Toastify has pre-defined transitions like Slide
, Zoom
, and Bounce
or you can create a transition from scratch.
import { Slide } from 'react-toastify';
<ToastContainer transition={Slide} />;
Localizing Toast Notifications
To further enhance the usability of applications that use multiple languages, use libraries such as react-intl
to localize the toasts of your React-Toastify with your application. Pass it into the toast
function, as the former would require user-inserted values.
import { useIntl } from 'react-intl';
const intl = useIntl();
toast.success(intl.formatMessage({ id: 'toast.successMessage' }));
Performance Considerations
React-Toastify was built to be lightweight and performant. Nevertheless, there are ways to optimize the performance even further:
- Use lazy loading to load the library when toasts are needed.
- Keep re-renders to a minimum by using separate components to manage toast logic.
New Features in React-Toastify
The new version, React-Toastify 9, is packed with exciting new features that will enhance your development experience:
- Notification Center: The useNotificationCenter hook can set up the notification center.
- Improved Accessibility: Improved keyboard navigation and screen reader support.
- Custom Toaster Container: You can now set a different container for
<ToastContainer />
. - Greatly Improved TypeScript Support: Well-enhanced TypeScript definitions for developers.
Benefits of using React-Toastify
- Simplicity: It takes just a few lines of code to get it up and running.
- Flexibility: Toaster can be customized to fit any application’s style.
- Scalability: It is appropriate for small applications or very complex enterprise applications.
- Accessibility: Traveling along the WCAG standard makes toast usable for everybody.
Final Words
True, React-Toastify is a flexible and powerful multimedia tool that makes it easy to integrate toast notifications for React applications. This versatile package takes care of everything from simple success messages to multifunctional notification centers. With so many updated features, the package becomes even more accessible and feature-rich for developers looking to improve user experience.
Knowing these features gives you the styling view of toast messages that could be visually appealing, informational, and user-friendly, increasing your application’s attractiveness and responsiveness.
Comments