Using react-hot-toast with Astro

Posted January 23, 2023

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

1. Install react-hot-toast

npm install react-hot-toast

2. 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.

import { Toaster } from "react-hot-toast";

export default (Component) => {
  return (props) => (
      <Toaster position="top-center" reverseOrder={false} />
      <Component {...props} />

3. Create a component called Button.tsx

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

4. Import Toastify.tsx into Button.tsx

Export the Toastify component with the Button as its argument.

import Toastify from "./Toastify";
import toast from "react-hot-toast";

export default function Toastify(function Button({message})) {
  return <button>{message}</button>

5. Create a function to trigger the toast

const notify = () => toast("Toast!");

6. 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>