Issues when importing from `index.ts` using app directory
Unanswered
Mr.Robot posted this in #help-forum
Mr.RobotOP
Please look into the following sandbox, where I highlight the issue.
https://stackblitz.com/edit/stackblitz-starters-fhjavm?file=components%2Fcomp-client.tsx
I have following structure of nextjs app
In
In
In
In
I am getting the following error
Why am I getting this error, only when I am importing
https://stackblitz.com/edit/stackblitz-starters-fhjavm?file=components%2Fcomp-client.tsx
I have following structure of nextjs app
components
┣ index.ts
┣ comp-client.tsx
â”— comp-server.tsx
app
â”— page.tsx
In
page.tsx, I have following codeimport { CompServer } from '@/components';
export default function Home() {
return <CompServer />;
}In
comp-client.tsx, I have following codeimport { useEffect } from 'react';
export const CompClient = () => {
useEffect(() => {}, []);
return <h1> Client</h1>;
}In
comp-server.tsx, I have following codeexport const CompServer = () => <h1> Server</h1>;In
index.ts, I have following codeexport * from './comp-client';
export * from './comp-server';I am getting the following error
You're importing a component that needs useEffect. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.Why am I getting this error, only when I am importing
comp-server in page.tsx12 Replies
it's because
useEffect only work in client component so you need to add 'use client' at the top of the file to mark it as a client componentMr.RobotOP
I get that. But I am only importing
comp-server and it should work as I am not importing comp-clientwell, it might be better to separate them
https://stackblitz.com/edit/stackblitz-starters-ju1jbp
https://stackblitz.com/edit/stackblitz-starters-ju1jbp
as you can see, I just put 'use client' in components/client/index.ts and it still render as client component
Mr.RobotOP
"I encountered a similar issue on my project. However, I am curious to know why it doesn't work without using the
use client directive. In my case, all the components are exported from the index.ts file. Some of them are directly imported in page.tsx, while others are imported in other components that are themselves using the use client directive."because it would mark the server component to become client component
Mr.RobotOP
Thank you for your help, Ray. I already know the solution, but I'm curious about why importing just the server components from index.ts throws an error. This is how es module works or this is implemented by Nextjs team.
more like how es module work and
'use client' is react stuff😆