How to use Server Components in Nextjs 13 with Chakra UI
Asked Answered
R

2

5

I'm trying to use React Server Component (with NextJS 13) in Chakra UI but I think it's not yet possible.

From Chakra UI docs (https://chakra-ui.com/getting-started/nextjs-guide): enter image description here

In my example I would like to fetch data in a Server Component and then render it

import { Text } from "@chakra-ui/react";

async function getData() {
  const res = await fetch("http://localhost:3000/api/products");
  if (!res.ok) {
    throw new Error("Failed to fetch data");
  }

  return res.json();
}

export default async function Page() {
  const data = await getData();
  return <Text>{data.length}</Text>;
}

As expected I get an error:

./node_modules/@chakra-ui/accordion/dist/chunk—JDQBKIKM.mjs ReactServerComponentsError: You're importing a that needs useState. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.

since I'm trying to import only client compatible component (Text) in my Server Side Component.

Any solution ?

Rosenblum answered 28/2, 2023 at 11:16 Comment(0)
F
8

As suggested in the docs, you can wrap the chakra-ui components in client components like so:

// text.jsx
"use client";
import { Text } from "@chakra-ui/react";
export default Text;

Now just import the Text Component from text.jsx, not chakra ui directly.

Fideism answered 28/2, 2023 at 11:48 Comment(1)
I don't understand how this solves the problem. Client components get rendered after server components. You're basically sending the server component to the client without Chakra's styles... You're not seeing this because it's fast. But if you actually inspect it, you'll see unstyled text field first in the initial html sent from the server. Then after hydration, it gets styled.Lava
B
3

Rather than making an individual file, you can do:

'use client';

export * from '@chakra-ui/react';
Barbaresi answered 9/7, 2023 at 20:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.