React์์ ์คํ์ผ์ ์ ํ๋ ๋ฐฉ๋ฒ์ ์ฌ๋ฌ๊ฐ์ง๊ฐ ์์ต๋๋ค. ๊ทธ ์ค์์ CSS-in-JS๋ JavaScript๋ฅผ ์ฌ์ฉํ์ฌ ์ปดํฌ๋ํธ์ ์คํ์ผ์ ์ ์ํ๋ ํจํด์ ๋๋ค. styled-components๋ emotion๊ณผ ๊ฐ์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ค์ด ์ด ํจํด์ ๊ตฌํํ๊ณ โฆ
React์์ ์คํ์ผ์ ์ ํ๋ ๋ฐฉ๋ฒ์ ์ฌ๋ฌ๊ฐ์ง๊ฐ ์์ต๋๋ค. ๊ทธ ์ค์์ CSS-in-JS๋ JavaScript๋ฅผ ์ฌ์ฉํ์ฌ ์ปดํฌ๋ํธ์ ์คํ์ผ์ ์ ์ํ๋ ํจํด์ ๋๋ค. styled-components๋ emotion๊ณผ ๊ฐ์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ค์ด ์ด ํจํด์ ๊ตฌํํ๊ณ ์์ต๋๋ค. ์ด๋ฌํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ค์ ํด๋ผ์ด์ธํธ ์ฌ์ด๋ ๋ ๋๋ง์ ์ต์ ํ๋์ด ์์ด, Next.js์ ๊ฐ์ SSR ํ๊ฒฝ์์ ์ฌ์ฉํ๊ธฐ ์ํด์๋ ๋ช ๊ฐ์ง ์ถ๊ฐ์ ์ธ ์ค์ ์ด ํ์ํฉ๋๋ค.
์๋ฒ ์ฌ์ด๋ ๋ ๋๋ง ์, ์ด๊ธฐ HTML์ ์์ฑํ๋ ์์ ์ ๋ชจ๋ styled-components์ ์คํ์ผ์ ์์งํ์ฌ ํฌํจ์์ผ์ผ ํฉ๋๋ค. ์ด๋ฅผ ์ํด ServerStyleSheet๋ฅผ ์ฌ์ฉํฉ๋๋ค:
์ฌ๊ธฐ์ ์ฌ์ฉ๋ useServerInsertedHTML ํ
์ Next.js์์ ์ ๊ณตํ๋ ํน๋ณํ ํ
์ผ๋ก, SSR ๊ณผ์ ์์ HTML์ ์ฃผ์
ํ ์ ์๊ฒ ํด์ค๋๋ค. ์ด๋ฅผ ํตํด ์๋ฒ์์ ์์ฑ๋ ์คํ์ผ์ด ์ด๊ธฐ HTML ์๋ต์ ํฌํจ๋ฉ๋๋ค.
export const StyledComponentRegistry = ({ children }: PropsWithChildren) => {
const [styleSheet] = useState(() => new ServerStyleSheet());
useServerInsertedHTML(() => {
const styles = styleSheet.getStyleElement();
styleSheet.instance.clearTag();
return <>{styles}</>;
});
if (typeof window !== 'undefined') return <>{children}</>;
return <StyleSheetManager sheet={styleSheet.instance}>{children}</StyleSheetManager>;
};
export default function RootLayout({
children,
}: Readonly<{
children: ReactNode;
}>) {
return (
<html lang="en">
<body>
<StyledComponentRegistry>
{children}
</StyledComponentRegistry>
</body>
</html>
);
}CSS-in-JS ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ ์คํ์ผ๋ง๋ค ๊ณ ์ ํ ํด์๊ฐ์ ํด๋์ค ์ด๋ฆ์ผ๋ก ์ฌ์ฉํฉ๋๋ค. ์๋ฒ ์ฌ์ด๋ ๋ ๋๋ง๊ณผ ํด๋ผ์ด์ธํธ ์ฌ์ด๋ ํ์ด๋๋ ์ด์ ๊ณผ์ ์์ ์ด ํด๋์ค ์ด๋ฆ๋ค์ด ์ผ์นํด์ผ ํ๋๋ฐ, ์ด๋ ๋ค์๊ณผ ๊ฐ์ ๋ฐฉ์์ผ๋ก ํด๊ฒฐ๋ฉ๋๋ค:
const nextConfig = {
compiler: {
styledComponents: {
// ๊ฐ๋ฐ ํ๊ฒฝ์์ ๋๋ฒ๊น
์ ์ํ ํด๋์ค๋ช
์ฌ์ฉ
displayName: process.env.NODE_ENV === 'development',
// SSR ์ง์ ํ์ฑํ
ssr: true,
// ๋ ์์ ๋ฒ๋ค ์ฌ์ด์ฆ๋ฅผ ์ํ ์ค์
minify: true
}
}
};ServerStyleSheet๊ฐ ์๋ฒ ์ฌ์ด๋์์ ์คํ์ผ์ ์์งํ๊ณ , ์ด๋ฅผ ์ด๊ธฐ HTML์ ํฌํจ์ํต๋๋ค.์ด๋ฌํ ์ค์ ๊ณผ ๋ฉ์ปค๋์ฆ๋ค์ด ํจ๊ป ์๋ํ์ฌ Styled-components ๋ผ์ด๋ธ๋ฌ๋ฆฌ๊ฐ Next.js์ SSR ํ๊ฒฝ์์ ์ ์์ ์ผ๋ก ๋์ํ ์ ์๊ฒ ํฉ๋๋ค.