Intro
While working on my latest side project, Code Anagrams, I wanted to display a notification whenever a user correctly answered an anagram as well as to display error messages a little more elegantly. At my current job, we use react-toastify for notifications and alerts, so I decided to reach for this package again and document my journey of configuring and implementing this particular solution.
Tutorial
Let's get started then.
More often than not, we need to implement notifications/alerts in multiple places within our codebase, so this is a perfect use case to create a util - let's call it "toast" - that we can simply import and use in various components.
In a utils
folder, create a folder called toast
and add an index.js
file. For our first step, we will need to install our npm package:
npm i react-toastify --save
and import it (along with associated CSS) to our index.js
file:
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
Fortunately, react-toastify provides you with a ton of versatility and you can configure your notifications in various ways, which is great. But for the purposes of this tutorial, I'll just set a couple of defaults for autoClose
and position
:
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
toast.configure({ autoClose: 2000, position: toast.POSITION.BOTTOM_CENTER });
Next, let's create our functions that render a successful notification (green) and an error alert (red):
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
toast.configure({ autoClose: 2000, position: toast.POSITION.BOTTOM_CENTER });
// add more config via the options object
const successToast = (message, options = {}) =>
toast.success(message, {
...options,
});
const errorToast = (message, options = {}) =>
toast.error(message, {
...options,
});
export { successToast, errorToast };
And there we have it! You can now import this util into your component like this:
import { successAlert, errorAlert } from "./utils/toast";
successAlert("Hey there!");
errorAlert("Oops, something went wrong!");
Conclusion
In this post, we created a simple, stylish and shareable toast util that should help with implementing notifications and alerts in our web applications.
If you feel like using react-toastify
in your app after reading this post, I strongly recommend heading over to the demo page and playing around with the different configurations.
Thanks for reading! 👋
Top comments (0)