Use react-toast-notifications to add toast notifications to a NextJS app

Share this video with your friends

Social Share Links

Send Tweet

A Toast is a non modal, unobtrusive window element used to display brief, auto-expiring windows of information to a user. They are used for status messages and persist between page changes until they have been seen. We'll use the react-toast-notifications library to add this functionality to a basic app.

Kevin Cunningham: [0:00] We start with a Next application, the host TPHS, the home page, the about page, have a link between them. We use our packet installer to install the React Toast notifications module.

[0:16] In order to use the Toast provider that comes with the module, we need to create an _app.js file. We go to the Next documentation and find the Custom App page, and copy the content of this block into our _app. This exposes the My thing component which otherwise isn't available to us in Next.

[0:46] We'll import the { ToastProvider } from "react-toast-notifications" and run our mounting component with our provider. My application works just as before, but if I look up my React dev tools, you'll see there's a ToastProvider wrapping the IndexPage and the AboutPage.

[1:13] I'll go to my IndexPage, and I will import { useToasts } from react-toast-notifications. I'll then destructure the addToast function from useToasts( ). Next, I'll add a button. This button will have an onClick handler, which will use the addToast function. We pass a string for our message on an options object.

[1:50] The only essential prop for options object is appearance, and in this case, we want it to be success. Now, clicking on the success button will provide us with a toast and notification that says, "Success!" Back in our ToastProvider, we can set autoDismiss to true and set a autoDismissTimeout to a time in milliseconds.

[2:21] Now, our message will dismiss after two seconds, without us having to manually do that. In the provider, it's also possible to provide a placement for where you would like the notifications to appear, bottom-center, top-left, whichever makes sense for your UI. React notification library also provide three other styles -- warning, info, and the error.

[2:48] Each phase can be customized and with these four types, we can provide detailed information to your users.