Search code examples
reactjsastrojs

astro hydration strategy `client:only="react"` not working with react js


This is my simple react component that is fetching the quote on the client side.

// quote.tsx

import React, { useEffect, useState } from "react";

const Quote = () => {
    const [quote, setQuote] = useState("");

    async function _fetchQuote() {
        const res = await fetch('https://api.adviceslip.com/advice');
        const data = res.json();
        const quote = data['slip']['advice'];
        setQuote(quote);
    }

    useEffect(() => {
        _fetchQuote();
    }, []);

    return <h1>
        <span>Quote: </span>
        <span>{quote}</span>
    </h1>;
}

export default Quote;

This is my astro component, where I have a basic layout and I want to show react component.

// quote-page.astro
---
import Base from "../layouts/Base.astro";
import Quote from "./components/quote";
---

<Base title="Qutoes">
    <Quote client:only="react" />
</Base>

I am using client:only="react" as the docs said but it seems to give me this error

06:39:24 PM [astro] reload /src/pages/quote-page.astro
 error   Unable to render `Quote`. When using the `client:only` hydration strategy, Astro needs a hint to use the correct renderer.
  Hint:
    Did you mean to pass `client:only="react|preact|solid-js|vue|svelte|lit"`? See https://docs.astro.build/en/reference/directives-reference/#clientonly for more information on client:only
  File:
    /home/.../src/page/quote-page.astro

Although I gave the value react as well it does not seem to be working I tried changing the file extension from quote.tsx to quote.jsx not worked.

My astro.config.ts is as follows

import { defineConfig } from 'astro/config';
import sitemap from '@astrojs/sitemap'; // https://astro.build/config

import vercel from "@astrojs/vercel/serverless";

// https://astro.build/config
export default defineConfig({
  site: "https://url",
  markdown: {
    syntaxHighlight: "prism"
  },
  integrations: [sitemap()],
  output: 'server',
  adapter: vercel(),
});

My dependencies in package.json

"devDependencies": {
    "astro": "^2.3.0",
    "path-browserify": "^1.0.1"
},
"dependencies": {
  "@astrojs/react": "^2.1.1",
  "@astrojs/rss": "^0.2.0",
  "@astrojs/sitemap": "^0.1.0",
  "@astrojs/vercel": "^3.2.4",
  "sass": "^1.52.1"
}

Solution

  • In astro.config.js, under integrations pass react() also.

    Reference here.