React-toastify is a handy library for adding toast notifications to your React application. These notifications are small messages that pop up on the screen to inform the user about an event. Here’s how you can add React-toastify to your React project:
Step 1: Installation
First, you need to install the react-toastify package. You can do this using npm or yarn:
or
Step 2: Setup
After installing the package, you need to include the CSS for the toast notifications. You can import it in your app’s entry file (typically App.js or index.js):
Step 3: Wrap Your Application with ToastContainer
ToastContainer is a component that will host the notifications. You need to include it once in your application layout, usually at a top-level component like App.js:
function App() {
return (
<div>
<ToastContainer />
{/* other components */}
</div>
);
}
Step 4: Using Toasts
Now that you have react-toastify set up, you can trigger toasts anywhere in your application. Here’s how to do it:
function MyComponent() {
const notify = () => {
toast(‘Wow so easy!‘);
};
return (
<button onClick={notify}>Notify!</button>
);
}
Configuration Options
The toast function and ToastContainer come with various options to customize the behavior and appearance of your notifications:
Positioning: You can specify where the toast will appear on the screen. For example, to display the toast at the top-right corner, you can set the position like so:
Auto Close: You can specify the auto close delay (in milliseconds). For example, to close after 3000 milliseconds (or 3 seconds):
Close Button & More: Customize the appearance, add a close button, change animation, etc.:
Handling Different Types of Toasts
react-toastify also provides methods for different types of notifications like success, error, info, and warning. Here’s how you might use them:
toast.error(‘This is an error toast!‘);
toast.info(‘This is an info toast!‘);
toast.warning(‘This is a warning toast!‘);
By following these steps, you can effectively integrate toast notifications into your React application, enhancing the user experience with timely and engaging feedback.