Using react-hot-toast with Astro

Using react-hot-toast with Astro

Posted Jan 23, 2023 ⋆ Last modified Nov 26, 2024
Table of Contents

Thank you to @happydev on the Astro discord who was able to figure this out.

Install react-hot-toast

Terminal window
npm install react-hot-toast

Create a component called Toastify.tsx

The Toastify component takes another component as its argument and returns it with a Toaster component imported from react-hot-toast.

Toastify.tsx
import { Toaster } from "react-hot-toast";
export default (Component) => {
return (props) => (
<br>
<Toaster position="top-center" reverseOrder={false} />
<Component {...props} />
</>
);
};

Create a component called Button.tsx

Button.tsx
export default function Button(message) {
return <button>{message}</button>;
}

Import Toastify.tsx into Button.tsx

Export the Toastify component with the Button as its argument.

Button.tsx
import Toastify from "./Toastify";
import toast from "react-hot-toast";
export default function Toastify(function Button({message})) {
return <button>{message}</button>
}

Create a function to trigger the toast

Button.tsx
const notify = () => toast("Toast!");

Set the client directive to client:load

If there is no client directive the HTML will be rendered without JavaScript. Reference

<ToastExample client:load message="Click me!" />

Final Result

import Toastify from "./Toastify";
import toast from "react-hot-toast";
export default Toastify(function Button({ message }) {
const notify = () => toast("Toast!");
return (
<>
<button onClick={notify}>{message}</button>
</>
);
});