next js notistack react components react js Uncategorized

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 notification libraries available for React one of them is Notistack.

Notistack is a slick and robust notification library for React providing versatile and highly customizable snackbars ( toast messages ).

Key features of Notistack include

  1. Stackable Notifications:- Stack in the name describes the ability of snack bars to be stacked simultaneously.
  2. Customizations:- Notistack provides extensive customization options, including variant styling, duration control, and the ability to add actions like buttons to notifications.
  3. Position:- Notifications can be positioned in various corners of the screen, allowing developers to place alerts where they are most effective.
  4. Dismissal Options:- Notifications can be dismissed manually or automatically after a specified duration. They can also be dismissed individually or all at once.

Now let’s see how we can use Notistack in our Nextjs or React.js applications,

Project setup

I hope you already have a Next js project, if not create a new Next js project with the following command.

npx create-next-app@latest my-app

I am creating a Nextjs project with app router for this tutorial but the process is similar for the older versions.

Initially, this is how my homepage looks like


export default function Home() {
  return (
    <main className="text-center" >
      
      <h1>Notistack</h1>
      
    </main>
  );
}

Step 1: Installing Notistack

Now open a terminal inside your project and run the following command to install notistack in your project.

npm install notistack
yarn add notistack

Link to NPM directory

Step 2: Basic Usage

We can set it to display Notistack snack bars either in a specific page or in the whole application

On a specific page or component

We place SnackbarProvider component anywhere in the components, but first we need to import it from notistack like below.

import { SnackbarProvider } from 'notistack';

and use it anywhere in your component

import { SnackbarProvider } from 'notistack';

export default function Home() {
  return (
    <main className="text-center" >

      <SnackbarProvider />
      
      <h1>Notistack</h1>

    </main>
  );
}

Now we need to use the enqueueSnackbar method from notistack to render snackbars. Here, I am adding a button that, when clicked, will call enqueueSnackbar to show the snackbar.

"use client"

import { SnackbarProvider, enqueueSnackbar } from 'notistack';

export default function Home() {
  return (
    <main className="text-center" >

      <SnackbarProvider />

      <h1>Notistack</h1>

      <button onClick={() => enqueueSnackbar('Hello Coders!')}>Show snackbar</button>


    </main>
  );
}

Output

In the whole project

With this method, we will be able to display the snackbar throughout our whole project by adding the provider just once in a root level component, ie. in the Nextjs app router root layout.js

Currently, this is my root layout

import { Inter } from "next/font/google";
import "./globals.css";

const inter = Inter({ subsets: ["latin"] });

export const metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={inter.className}>{children}</body>
    </html>
  );
}

Now we are going to use SnackbarProvider to wrap our whole app so that we’ll be able to use useSnackbar hook to show and close Snackbars, like below.

import { Inter } from "next/font/google";
import "./globals.css";

import { SnackbarProvider } from 'notistack';

const inter = Inter({ subsets: ["latin"] });

export const metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <SnackbarProvider>
          {children}
        </SnackbarProvider>

      </body>
    </html>
  );
}

This isn’t going to work as Notistack requires the component to be a client component so we are going to create an additional component called SnackbarProviderClient.js and export SnackbarProvider as Notistack provider i.e now a client-side provider as we have used use client on the top.

'use client'

export { SnackbarProvider as NotistackProvider } from 'notistack'

Now in the root layout.js we can import NotistackProvider from SnackbarProviderClient.js


import { Inter } from "next/font/google";
import "./globals.css";

import { NotistackProvider } from "./SnackbarProviderClient";

const inter = Inter({ subsets: ["latin"] });

export const metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <NotistackProvider>
          {children}
        </NotistackProvider>
      </body>
    </html>
  );
}

Now we can import and use useSnackbar hook from Notistack in any client component in our project.

For example, in page.js we have restructured the enqueueSnacbar method from useSnackbar to render snack bars.

"use client"

import { useSnackbar } from 'notistack';

export default function Home() {

  const { enqueueSnackbar } = useSnackbar();

  return (
    <main className="text-center" >

      <h1>Notistack</h1>

      <button onClick={() => enqueueSnackbar('Hello Coders!')}>Show snackbar</button>



    </main>
  );
}

Another method we can use is closeSnackbar to close the snackbars programmatically

Most used Props

Notistack API provides lots of props and customizations let’s talk about some of the most used props that might be useful for you too.

Maximum snackbars

This can used to limit the number of props we can show at once.

To use this props we can just pass maxSnack value in the SnackbarProvider in our case its NotistackProvider in the root layout.js


import { Inter } from "next/font/google";
import "./globals.css";

import { NotistackProvider } from "./SnackbarProviderClient";

const inter = Inter({ subsets: ["latin"] });

export const metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={inter.className}>

        <NotistackProvider maxSnack={3}>
          {children}
        </NotistackProvider>

      </body>
    </html>
  );
}

Output

Hide duration

We can set the duration after which the snackbars disappear

We can set it in either the main Provider (SnackbarProvider) or in individual snackbars

<SnackbarProvider autoHideDuration={1000}>
  <App />
</SnackbarProvider>

const message = 'Your notification here'
enqueueSnackbar(message, { autoHideDuration: 1000 })

Prevent duplicate

Sometime its possible that same message gets render multiple times, but we can prevent this by setting preventDuplicate to true. If a user-defined key is passed in the options of enqueueSnackbar, then this prevents snackbars with the same key from being displayed multiple times.

<SnackbarProvider preventDuplicate>
  <App />
</SnackbarProvider>

const message = 'You only see me once.'
enqueueSnackbar(message, { 
  preventDuplicate: true
})

To know about more of these props visit the official documentation.

API

Notistack API provides lots of features and customization for both Provider and Renderer ( enqueueSnackbar ). Some of them are mutual i.e., can be used in both but some are specific to each.

Mutual Props

These props can be passed in SnackbarProvider props, as well as options parameter of enqueueSnackbar.

Mutual PropsDescriptionTypeDefault
SnackbarPropsProperties applied to the Snackbar root element.Object
TransitionComponentThe component used for the transition. See how you can use a different transition: custom transitionComponentSlide
TransitionPropsProperties applied to Transition component.Object
actionCallback used for getting action(s). actions are mostly buttons displayed in Snackbar.React.ReactNode | func
anchorOriginThe anchor of the Snackbar.{ horizontal: left | center | right, vertical: top | bottom }{ horizontal: left, vertical: bottom }
autoHideDurationNumber of milliseconds before automatically calling the onClose function. Set to ‘null’ to disable auto-closing.number | null5000
classNameCustom class name.string
disableWindowBlurListenerIf true, the autoHideDuration timer will expire even if the window is not focused.booleanfalse
hideIconVariantHides iconVariant if set to true.booleanfalse
onCloseCallback fired before snackbar requests to get closed.func
preventDuplicateIgnores displaying multiple snackbars with the same message.booleanfalse
styleCustom inline styles.React.CSSProperties
transitionDurationDuration for the transition, in milliseconds.{ enter: 225, exit: 195 }{ enter: 225, exit: 195 }
variantEasily display different variants of snackbars.default | error | success | warning | infodefault
onEnterCallback fired before the transition is entering.func
onEnteredCallback fired when the transition has entered.func
onExitCallback fired before the transition is exiting.func
onExitedCallback fired when the transition has exited.func

SnackbarProvider props

SnackbarProvider PropsDescriptionTypeDefault
ComponentsMapping between variants and a custom component.Object
childrenMost of the time this is your App. every component from this point onward will be able to show snackbars.React.ReactNode | React.ReactNode[]
classesOverride or extend the styles applied to the container component or Snackbars.Object
denseDenser margins for snackbars. Recommended to be used on mobile devices.booleanfalse
domRootValid HTML Node element, used to target ReactDOM.createPortal. Apply position: absolute to SnackbarContainer.HTMLElement
iconVariantMapping between variants and an icon component.Object
maxSnackMaximum snackbars that can be stacked on top of one another.number3

enqueueSnackbar Options

enqueueSnackbar OptionsDescriptionTypeDefault
keyUnique identifier to reference a snackbar.string | numberrandom unique string
persistSnackbar stays on the screen, unless it is dismissed (programmatically or through user interaction).booleanfalse

Conclusion

Hope this tutorial helped you to use Notistack in your project, for more information visit the official documentation . Thanks for visiting to watch this tutorial in video format subscribe to our YT Channel.

Related Posts

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 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…

lucide icons

Using Lucide React Icons in Nextjs | React js

Lucide offers a sleek and versatile icon library that seamlessly integrates with your Next.js or React applications. Let’s explore how to leverage Lucide for beautiful, customizable icons: Lucide…

Best toast notification libraries for Next js

One of the most liked aspects of the React Ecosystem is that you can find components and libraries for almost everything you want to implement in your React…

Leave a Reply

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