Simple Notifications with React Toastify: A Beginner Guide
The importance of notifications in terms of user experience is undeniable. Information messages, success notifications, error alerts, and more, provide feedback on the state of the application, offering a more user-friendly and interactive experience. However, managing and presenting notifications properly can be complex. This is where React Toastify comes in.
React Toastify is a library that allows you to create customizable notifications in your React applications. With the ability to display both successful and erroneous situations as well as informational messages, Toastify offers a flexible solution for providing feedback to users.
React Toastify can be easily added to your project via NPM. First, add the library to your project by running the following command in your terminal:
npm install --save react-toastify
After installing React Toastify, the first thing we need to do is to import the CSS styles. In your index.ts file, simply add:
import 'react-toastify/dist/ReactToastify.css'
To leverage the full power of React Toastify, it's a good practice to create a dedicated function for displaying notifications. Here, in the alertNotification.ts file, we define a function that takes two parameters: status and message. Depending on the status, either a success or an error toast is displayed.
Now, let's see how to use our alertNotification function in a real-world example. In the SaleRegister.tsx file, we import the alertNotification function.
When the user attempts to register as a seller, our application makes a request to the server. Depending on the server response, we call alertNotification with an appropriate status and message.
import alertNotification from '.../utils/alert'
// After a successfull operation
alertNotification('success', 'The store is added successfuly')
// In case of an error
alertNotification('error', err.response.data.message)
Finally, we need to render the ToastContainer in our component. This is the component that will actually render the toast notifications.
In SaleRegister.tsx, we include the ToastContainer component:
import { ToastContainer } from 'react-toastify'
return (
<div>
....
<ToastContainer />
</div>
)
This guide demonstrates a practical way to utilize the React Toastify library. By creating a dedicated function for notifications and using it in a component, we can effectively manage and display notifications in a real-world React application. Remember that you can always refer to the official React Toastify documentation for more customizations and options.