Skip to content

Instantly share code, notes, and snippets.

@fvaldes33
Last active July 22, 2024 15:06
Show Gist options
  • Save fvaldes33/0f858432b55a200cf2133530b72a696f to your computer and use it in GitHub Desktop.
Save fvaldes33/0f858432b55a200cf2133530b72a696f to your computer and use it in GitHub Desktop.
Migrate to the new sonner toast without rewriting your old toasts
import { Toaster as Sonner, toast as sonner } from "sonner";
const Toaster = ({ ...props }: ToasterProps) => {
return (
<Sonner
theme={"light"}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton:
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
);
};
type ToastProps = {
title?: React.ReactNode;
description?: React.ReactNode;
variant?:
| "default"
| "destructive"
| "success"
| "info"
| "warning"
| "error"
| "message";
action?: {
label: string;
onClick: () => void;
};
};
type ToastFn = Omit<
typeof sonner,
"dismiss" | "custom" | "promise"
>;
function toast({ title, variant = "info", ...props }: ToastProps) {
let resolvedVariant = variant;
if (variant === "default") resolvedVariant = "info";
if (variant === "destructive") resolvedVariant = "error";
const fn = sonner[resolvedVariant as keyof ToastFn];
fn(title, {
...props,
});
}
export { Toaster, toast, sonner };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment