next js react js

Using Sonner Toast in Next Js / React

Sonner is an excellent React component for displaying Toast messages in Next.js or React.js apps. While there are similar packages like React Toastify that also facilitate the display of toast messages, Sonner stands out for its smooth performance and elegant presentation. It is so smooth and gives a very elegant feeling while displaying toast messages.

Sonner Toast provides many types of toast messages and has a feature to add custom styling and components to show in the Toast messages.

Enough talking let’s see how we can use Sonner in our Nextjs app ( you can follow this tutorial for React also :D).

Step 1: Setting up the project

As Sonner is a React js component we can use it in any of both frameworks, the process is almost the same for both.

Here I have created a React application

In this project, you can see I have created a components folder, that I am later going to use to create Toast components.

Step 2: Installing Sonner

Use the below command to install sonner

npm i sonner
pnpm i sonner
yarn add sonner
bun add sonner

Step 3: Showing basic toast

To show a toast message, we need to utilize two components from the Sonner library.

  1. Toaster: This component serves as the wrapper for all displayed messages, although we can place it any where its preferred to be placed in our root component.
  2. Toast: A method provided by Sonner to transmit messages to the library, triggering the display of a toast message.

Here I am going to put <Toaster /> component in App.js

import { Toaster } from "sonner";
import "./App.css";

function App() {

  return (
    <>
      <div className="app">

        <Toaster />

        <h1 className="text-4xl">Hello Coders!</h1>
        
      </div>
    </>
  );
}

export default App;

Now I am going to use Toast funtion to show a messege

Typically, we would employ our business logic to programmatically show a toast message. However, in the meantime, I am adding a button. Upon clicking the button, it will trigger a function notify(). Inside that function, I will call the Toast function and pass a message string.

import { Toaster, toast } from "sonner";
import "./App.css";

function App() {

  const notify = () => toast('This is a sonner toast');

  return (
    <>
      <div className="app">
        
        <Toaster />

        <h1 className="text-4xl">Hello Coders!</h1>

        <button onClick={notify}>
          Show the toast
        </button>
      </div>
    </>
  );
}

export default App;

Output

Great we have successfully rendered a sonner toast.

Step 4: Customization

Now, there are numerous customizations and variations available. We can modify the toast’s position, type, theme, and many other options. Visit the official documentation for live demos.

Types

Thsese are available types of toast messeges we can render.

  1. Default
  2. Description
  3. Success
  4. Info
  5. Warning
  6. Error
  7. Action
  8. Promise
  9. Custom

1. Success

Lets try success first, to use a different variation we just need to add type after toast funtion.

For example .success

const notify = () => toast.success("Hello coders it was easy!");

Output

Here you can see these toasts are mono chromatic, to show colorful toast we can use richColors props in <Toaster />.

 <Toaster richColors />

2. Warning

const notify = () => toast.warning("Hello coders warning!");

3. Error

const notify = () => toast.error("Hello coders error!");

4. Action

We can render an action button along with messege, clicking on it will call the function passed to onClick listener.

const notify = () => toast('My action toast', {
    action: {
      label: 'Action',
      onClick: () => console.log('Action!'),
    },
  });;

5. Promise

Whenever we create a promise like seaeching or submiting a request, we can use sonner promise toast.

We pass a promise in toast.promise() and Initially it will show loading messege that we set, once the promise is resolved it will show the success messege, we can even include result data in success messege. Check out this example:

toast.promise(myPromise, {
  loading: 'Loading...',
  success: (data) => {
    return `${data.name} toast has been added`;
  },
  error: 'Error',
});

6. Loading

When you want to handle varous states manually instead of using promise you can use sonner loading toast, it renders a toast with a loading spinner.

Other Props

Now there are still many customization available and different props you can use to custumize the toast messeges as per your need some of the props and their funtionalities are as below.

PropertyDescriptionDefault
descriptionToast’s description, renders underneath the title.-
closeButtonAdds a close button which shows on hover.false
invertDark toast in light mode and vice versa.false
importantControl the sensitivity of the toast for screen readersfalse
durationTime in milliseconds that should elapse before automatically closing the toast.4000
positionPosition of the toast.bottom-right
dismissibleIf false, it’ll prevent the user from dismissing the toast.true
iconIcon displayed in front of toast’s text, aligned vertically.-
actionRenders a primary button, clicking it will close the toast.-
cancelRenders a secondary button, clicking it will close the toast.-
idCustom id for the toast.-
onDismissThe function gets called when either the close button is clicked, or the toast is swiped.-
onAutoCloseFunction that gets called when the toast disappears automatically after it’s timeout (duration` prop).-
unstyledRemoves the default styling, which allows for easier customization.false
actionButtonStylesStyles for the action button{}
cancelButtonStylesStyles for the cancel button{}

Conclusion

Overall sonner toast is all in one package for you if you want to display smooth toast messeges in your applicaiton.

I hope you find this tutorial easy and helpful, stay tuned to Tutorend.

Related Posts

Google Analytics in Nextjs

Add Google Analytics in Nextjs with Quickest Method

Vercel has recently been adding a feature called the third-party library, which allows us to integrate various third-party tools like Google Analytics in the most performant way possible…

How To Install and Use Flowbite in Next js

Flowbite is an open-source library of UI components based on the utility-first Tailwind CSS framework featuring dark mode support, a Figma design system, templates, and more. It provides…

Using Notistack in Nextjs | React js

Showing toast messages in react apps is a common feature to add, as it’s one of the quickest ways to give feedback to users. There are many toast…

Using React Feather Icons in Next js

Feather Icons is a collection of sleek and beautiful icons that you can use in your projects in different ways and integrate seamlessly with React-based applications. To use…

find unused npm packages

Find and Remove Unused NPM Packages from Your Project

While building apps in an NPM environment it’s easy to accumulate lots of NPM packages in our app that we don’t even need, these package slows down our…

Using Bootstrap Icons in Next js | React

Bootstrap Icons is a Free, high-quality, open-source icon library with over 2,000 icons. You can use them as you like SVGs, SVG sprite, or web fonts. We can…

Leave a Reply

Your email address will not be published. Required fields are marked *