An Introduction to React-Hot-Toast
Add Notifications to your React application seamlessly with React-Hot-Toast
Introduction
Sometimes, you might need to display a quick message to inform your users about the current state of your application or let them know if a particular request (e.g. delete an item) was successful or not. In the past, this was done with alerts
, but alerts can be annoying as they cannot be styled and also prevent the user from accessing the rest of the application until they manually close the alert. Because of this, many developers resorted to reinventing the wheel, by creating modals
and setting a timeout so the popup disappears after a specific time. While this method works effectively, it can sometimes be overkill and even time-consuming to create a separate component for simple notifications like displaying a success/error message.
React-Hot-Toast to the rescue!
React-Hot-Toast provides a fast, intuitive and simple way to add notifications to your React application with customizable styles and icons (emoji support).
Getting Started
Install the package in the root directory of your application
npm install react-hot-toast
Import it into the component you want to use it
import toast,[Toaster] from 'react-hot-toast';
The Toaster
object contains the styles and settings for displaying the toast
and should be placed at the bottom of the component in a self-closing tag. (Note: for the rest of this article I'll be referring to notifications as toast as they are called in the documentation because I think it's a witty name)
export const App = () => {
return (
<div className='App' >
//...
<Toaster />
</div>
)};
The toast
object contains different methods for adding toasts depending on the type of notification (toast) you want to display.
Types of Toast
- Blank: This is the most basic form of toast. When you pass content to be displayed directly to the toast object, it is rendered with default styles without any icon.
toast('hello world')
- Custom: This creates a custom toast without default styles. You can also add JSX inside the toast.
toast.custom(<div>Hi There!</div>)
- Success: Display a success toast with default styles and a green checkmark icon. You can also define custom styles and icons (more on this later).
toast.success('login successful')
- Error: Display an error toast with default styles and a red
X
icon. You can also define custom styles and icons (more on this later).toast.error('unable to fetch data')
- Loading: This is used to display a loading message indefinitely (with an infinite duration). Note, if you're using this, you would need to programmatically dismiss/remove the toast (more on how to remove toasts later).
toast.loading('fetching data...')
- Promise: This is an intuitive combination of the previous three types of toast used for invoking a toast on a promise.
// promise
const myPromise = fetchData();
toast.promise(myPromise, {
loading: 'fetching data...',
success: 'here is your data',
error: 'Error connecting to database',
})
Removing/Dismissing Toasts
There are two ways to remove a toast if you are using a toast with an infinite duration or you want to dismiss it before the duration ends:
- Dismiss: This method triggers the exit animation property which removes the animation after 1 second.
To dismiss a single toast, pass the ID of the toast to the
toast.dismiss()
method. (Note: each toast returns an ID that is unique to it; you can use this ID to manipulate the toast.)
// get the ID of the toast
const toastId = toast.loading('connecting to server...');
// ...
toast.dismiss(toastId);
To dismiss all toasts, simply call the dismiss
method without an ID:
toast.dismiss()
- Remove: To remove toast immediately without any delay or animation, use the toast.remove()` method. This works exactly like the dismiss method but instantly removes the toast without calling the exit animation. This could be useful in case of an error in your application.
const toastId = toast.loading('connecting to server...');
// ...
// remove a single toast
toast.remove(toastId);
// remove all toast at once
toast.remove();
You can also use the toast ID to update the toast instead of removing it. So we can update the loading toast we created earlier using the ID:
// update the loading toast to a success toast
toast.success('This worked', {
id: toastId,
});
Defining custom styles
Each toast
method accepts an additional object which can be used to define custom styles. For example, we can add custom styles to the success
toast we created earlier like this:
toast.success('login successful', {
// set duration and position
duration: 4000,
position: 'top-center',
// Styling
style: {
minWidth: '100px'
},
// add more styles within your stylesheet
className: '',
// Custom Icon
icon: '๐',
// Change theme color
iconTheme: {
primary: '#000',
secondary: '#fff',
},
)
Same thing for a promise toast:
toast.promise(
myPromise,
{
loading: 'fetching data...',
success: 'here is your data',
error: 'Error connecting to database',
},
{
style: {
minWidth: '200px',
},
// style the success toast
success: {
duration: 4000,
icon: '๐ฅ',
},
// style the error toast
error: {
duration: 5000,
icon: '๐ง',
},
}
);
Adding global styles to the Toaster
object
You can add an object with global styles like toast position, theme color, etc. to the Toaster
object instead of defining custom styles for each toast.
<Toaster
//toast position
position="top-center"
// reverse position
reverseOrder={false}
// margin between two toasts
gutter={8}
// class name for styling
containerClassName=""
// add more custom styles here
containerStyle={{}}
// custom styling for all toasts
toastOptions={{
// Define default options
className: '',
duration: 4500,
style: {
background: '#363636',
color: '#fff',
},
// Default options for specific types
success: {
duration: 3000,
theme: {
primary: 'blue',
secondary: 'white',
},
},
}}
/>
Toast position
set the position of the toast. The default is top-center
.
Available Options:
- top-left
- top-center
- top-right
- bottom-left
- bottom-center
- bottom-right
toastOptions
works like the additional object we used earlier to style the success/promise toasts. The difference is that this applies to all toasts within the component in which this was defined instead of one toast alone.
Summary
This was just a basic introduction to React-Hot-Toast and does not cover all the things you can do with it. However, this covers all you need to get started and to add beautiful and dynamic push notifications to your React project; unless you are looking for something more complex. I would be glad to answer your questions if you have any. You can also check out their documentation for more in-depth and advanced features.
Thanks for reading.