Search code examples
javascriptreactjsnext.jsstyled-components

How do I use StyledComponents in the Next.js 13 app folder?


From the Next.js docs:

Warning: CSS-in-JS libraries which require runtime JavaScript are not currently supported in Server Components.

The following libraries are supported in Client Components in the app directory:

  • styled-jsx
  • styled-components
  • style9

Questions

  1. Does that mean I have to use the use-client directive in every component that uses StyledComponents?
  2. If so, is it possible to write all StyledComponents in one file, with the use-client directive at top, and then just import these Client Components as needed into the Server Components?
  3. Will the approach above somehow turn the Server Components into Client Components?
  4. The Next.js docs state that all components within the app directory are Server Components by default. If we save a component outside the app directory and import it into a Server Component in the app directory, will that imported function then also become a Server Component?

Solution

  • I'll try my best to answer your questions.

    1. Yes you have to use it every time you use StyledComponents.
    2. It is possible but Next.js will render it as Client Component even though you import it inside a Server Component.
    3. From the docs, it will make the component into Client Component if the page that you're trying to render are all components with 'use client' directive. Next.js will render it server side if there are any Server Component inside the page and send the rest to the client.
    4. Yes it will become server components as long as the components that are imported isn't using the 'use client' directive.

    Hope it helps.