How to Use React Toastify With NextJS

Posted by Chaitanya Shahare on Sat, Oct 5, 2024

React Toastify is a popular library for showing toasts in React applications. It’s easy to use and has a lot of customization options. In this post, we will see how to use React Toastify with NextJS.

1. Installation

npm install --save react-toastify

2. Import CSS

app/layout.tsx

import "react-toastify/dist/ReactToastify.css";

3. New component for ToastContainer

app/components/next-toast-container.tsx

"use client";
export { ToastContainer } from "react-toastify";

We are doing this because, by default all the components in NextJS are server-side rendered, but we want to use the ToastContainer on the client-side only. If we make the app/layout.tsx component client-side rendered, then the whole app will be client-side rendered, which is not what we want.

That’s why we are essentially creating a new component that will be client-side rendered & just exports the ToastContainer from react-toastify.

4. Import Toast container

app/layout.tsx

import { ToastContainer } from "@/components/next-toast-container";
import { Bounce } from "react-toastify";

5. Use Toast container

app/layout.tsx

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <div className="max-w-md mx-auto min-h-screen relative">
            {children}
        </div>
        <ToastContainer
          position="top-right"
          autoClose={5000}
          hideProgressBar={false}
          newestOnTop={false}
          closeOnClick
          rtl={false}
          pauseOnFocusLoss
          draggable
          pauseOnHover
          theme="colored"
          transition={Bounce}
        />
      </body>
    </html>
  );
}

6. Use toast anywhere in the app

toast('🦄 Wow so easy!', {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
transition: Bounce,
});

Conclusion

This is how you can use React Toastify with NextJS. It’s a simple and easy to use library for showing toasts in your app.

Resources