DEV Community

Cover image for How to Set Up sonner in Your Remix Project
Muhammad Hasbi
Muhammad Hasbi

Posted on • Edited on

How to Set Up sonner in Your Remix Project

If you're a developer who is confused about using the sonner library on Remix, follow the steps below to get it working.

Step 1: Install the Package

First, install the package in your project using npm or yarn:

npm install sonner
Enter fullscreen mode Exit fullscreen mode

or

yarn add sonner
Enter fullscreen mode Exit fullscreen mode

Step 2: Add the Styles

Next, add the necessary CSS for styling the toasts. You can copy the content from the official styles.css file here: https://github.com/emilkowalski/sonner/blob/main/src/styles.css

Save this file in your project, for example, at /src/styles/sonner.css, and make sure to import it into your root.tsx.

....
import "./styles/app.css";
import "./styles/sooner.css";
Enter fullscreen mode Exit fullscreen mode

Step 3: Add the <Toaster /> Component

Then, add the <Toaster /> component to the root of your application so it can be rendered on any page.

For example, in a Remix application, you can add it to your app/root.tsx file within the Layout component. Make sure to import it first.

import { Toaster } from 'sonner';

export function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <Meta />
        <Links />
      </head>
      <body>
        {children}
        {/* Add the Toaster component here */}
        <Toaster position="top-center" richColors />
        <ScrollRestoration />
        <Scripts />
      </body>
    </html>
  );
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Trigger a Toast

Finally, you can trigger a toast from any component. Import the toast function and call it from an event handler, like a button click.

import { toast } from 'sonner';

function MyComponent() {
//....
useEffect(() => {
  if(errors.input){
    toast.error(errors.input)
  }
},[errors])

return (
    <button onClick={() => toast("A toast has appeared!")}>
      Show Toast
    </button>
  );
}
Enter fullscreen mode Exit fullscreen mode

Customization: Enable Rich Colors

To enable colorful toasts for different types (like success, error, or warning), add the richColors prop to the <Toaster /> component, as shown in the Step 3 example.

If you run into any trouble, let me know in the comments below.

Top comments (0)