Styling[Next.js]

SnowCat·2023년 4월 27일
0

Next.js

목록 보기
15/16
post-thumbnail

CSS Module

  • 리액트에서와 동일하게 module.css파일을 사용해 각 파일별로 css를 사용할 수 있음
.dashboard {
  padding: 24px;
}
import styles from './styles.module.css';

export default function DashboardLayout({ children }: {
  children: React.ReactNode
}) {
  return <section className={styles.dashboard}>{children}</section>;
}

External Stylesheets

  • css파일을 작성하거나 이미 제작된 css 파일을 가져올 수 있음
import 'bootstrap/dist/css/bootstrap.css';

export default function RootLayout({ children }: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body className="container">{children}</body>
    </html>
  );
}

Global Styles

  • 모든 디렉터리에 전역적으로 사용되는 css파일은 app/global.css파일에 지정
    _app.js에서만 import 가능한 pages 디렉터리와는 다르게 app 디렉터리에서는 필요한곳 어디에서는 글로벌 css를 가져올 수 있음
body {
  padding: 20px 20px 60px;
  max-width: 680px;
  margin: 0 auto;
}
import './global.css';

export default function RootLayout({ children }: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}

Tailwind CSS

  • 유틸리티 클래스를 활용하는 Tailwind css 역시 사용 가능
  • 프로젝트 폴더에서 다음 명령어를 수행해 tailwind.config.js, postcss.config.js 파일을 생성
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
  • postcss.config.js 수정없이 tailwind.config.js파일만을 수정하면 tailwind css 상요 가능
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx,mdx}", // app 디렉터리 추가
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",

    // src 디렉토리 사용시
    "./src/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
  • Tailwind css 선택자를 css 파일에 추가하기 위해 globals.css에 다음 구문 추가
@tailwind base;
@tailwind components;
@tailwind utilities;
  • global css를 root 레이아웃에 import하면 tailwind css 클래스 사용이 가능해짐
export default function Page() {
  return (
    <h1 className="text-3xl font-bold underline">
      Hello, Next.js!
    </h1>
  )
}

CSS-in-JS

  • styled-jsx, styled-components등의 CSS in js 라이브러리 역시 사용 가능함
  • 단, 런타임에서 자바스크립트가 필요한 라이브러리의 경우 서버 구성 요소에서는 사용 불가능
  • 사용을 위해서는 CSS 규칙을 수집할 style registry가 필요하고, useServerInsertedHTML을 사용해 HTML에 규칙을 집어넣으며, 클라이언트에서 이를 렌더링하게 됨
    ex) styled.jsx
// app/registry.tsx
'use client';

import React, { useState } from 'react';
import { useServerInsertedHTML } from 'next/navigation';
import { StyleRegistry, createStyleRegistry } from 'styled-jsx';

export default function StyledJsxRegistry({
  children,
}: {
  children: React.ReactNode;
}) {
  const [jsxStyleRegistry] = useState(() => createStyleRegistry());

  useServerInsertedHTML(() => {
    const styles = jsxStyleRegistry.styles();
    jsxStyleRegistry.flush();
    return <>{styles}</>;
  });

  return <StyleRegistry registry={jsxStyleRegistry}>{children}</StyleRegistry>;
}

// app/layout.tsx
import StyledJsxRegistry from './registry';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html>
      <body>
        <StyledJsxRegistry>{children}</StyledJsxRegistry>
      </body>
    </html>
  );
}

styled-components

// app/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>
  );
}

// app/layout.tsx
import StyledComponentsRegistry from './lib/registry';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html>
      <body>
        <StyledComponentsRegistry>{children}</StyledComponentsRegistry>
      </body>
    </html>
  );
}

Sass

  • 다른 스타일링 방법과 마찬가지로 Sass 역시 사용가능
  • sass 패키지를 설치하고 설정을 구성한 다음 사용하면 됨

설치 커맨드

npm install --save-dev sass

Sass 컴파일러 설정이 필요하면 next.config.js의 sassOptions 옵션 사용

const path = require('path');

module.exports = {
  sassOptions: {
    includePaths: [path.join(__dirname, 'styles')],
  },
};

ex)

$primary-color: #64ff00;

:export {
  primaryColor: $primary-color;
}
import variables from './variables.module.scss';

export default function Page() {
  return <h1 style={{ color: variables.primaryColor }}>Hello, Next.js!</h1>;
}

출처:
https://beta.nextjs.org/docs/styling/css-modules
https://beta.nextjs.org/docs/styling/tailwind-css
https://beta.nextjs.org/docs/styling/global-styles
https://beta.nextjs.org/docs/styling/css-in-js
https://beta.nextjs.org/docs/styling/external-stylesheets
https://beta.nextjs.org/docs/styling/sass

profile
냐아아아아아아아아앙

0개의 댓글