Is styled components feasible for next app router? #50473
-
Since, the styled components make use of contexts I'm unable to do
so, for every single components even without client side states I have to do 'use client'. Because of which I see page flickerings. How can we render styled components server side in app router? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 5 replies
-
Have you configured the |
Beta Was this translation helpful? Give feedback.
-
In Example: // [lib/registry.tsx]
'use client';
import React, { useState } from 'react';
import { useServerInsertedHTML } from 'next/navigation';
import { ServerStyleSheet, StyleSheetManager } from 'styled-components';
export default function StyledComponentsRegistry({
children,
}: {
children: React.ReactNode;
}) {
// Only create stylesheet once with lazy initial state
// x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet());
useServerInsertedHTML(() => {
const styles = styledComponentsStyleSheet.getStyleElement();
styledComponentsStyleSheet.instance.clearTag();
return <>{styles}</>;
});
if (typeof window !== 'undefined') return <>{children}</>;
return (
<StyleSheetManager sheet={styledComponentsStyleSheet.instance}>
{children}
</StyleSheetManager>
);
} Then import Example: // [app/layout.tsx]
import StyledComponentsRegistry from './lib/registry';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html>
<body>
<StyledComponentsRegistry>{children}</StyledComponentsRegistry>
</body>
</html>
);
} By doing this, you'll be able to use the For more information, look here. |
Beta Was this translation helpful? Give feedback.
-
What about styled-component@5? Is it possible to use with nextjs app-router? |
Beta Was this translation helpful? Give feedback.
In
App Router
, usestyled-components API
to create a global registry component.Example: