reactjsserver-side-renderingpreactastrojs

React component in Astro cannot use the window object


I'm Using preact in my Astro project. Which works fine until I added `window

ReferenceError: window is not defined

Now I know that Astro does SSR but in this case its a React component icw client:load

So, in index.astro I have

  <Counter count={count} client:load>
        <h1>Hello, Preact 1!</h1>
  </Counter>

Counter is my React component:

export default function Counter({ children, count }) {
    const href = window.location.href;

    return (
        <>
            ...
        </>
   );
}

How can I fix this in my React component?


Solution

  • client:load still renders the initial view on the server, before hydrating it on the client.

    client:only skips HTML server-rendering.

      <Counter count={count} client:only>
            <h1>Hello, Preact 1!</h1>
      </Counter>