styled-componentsでスタイルを定義する

styled-components は、JavaScriptやTypeScript内にCSSを書く CSS-in-JS ライブラリです。コンポーネント単位でスタイルを完結でき、スコープも自動で分離されます。


1. インストール

npm install styled-components
npm install --save-dev @types/styled-components  # TypeScript の場合

2. 基本的な使い方

import styled from 'styled-components';

const Box = styled.div`
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 8px;
`;

const App = () => {
  return 
<Box>これはstyled-componentsのBoxです</Box>;
};

3. propsでスタイルを動的に変える

const Button = styled.button<{ primary?: boolean }>`
  background-color: ${props => (props.primary ? 'blue' : 'gray')};
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
`;

const App = () => {
  return (
    <>

<Button>Default</Button>
      <Button primary>Primary</Button>
    </>
  );
};

4. ネストや擬似クラスもOK

const Card = styled.div`
  padding: 20px;

  &:hover {
    background-color: #eef;
  }

  h2 {
    font-size: 1.25rem;
  }
`;

5. グローバルスタイルの定義

import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
    font-family: sans-serif;
  }
`;

const App = () => (
  <>
    <GlobalStyle />
    <MainComponent />
  </>
);

6. ThemeProvider を使ってテーマ適用

import { ThemeProvider } from 'styled-components';

const theme = {
  colors: {
    primary: '#0d6efd',
  },
};

const Title = styled.h1`
  color: ${({ theme }) => theme.colors.primary};
`;

const App = () => (
  <ThemeProvider theme={theme}>

<Title>テーマカラー適用</Title>
  </ThemeProvider>
);

コメントを残す 0

Your email address will not be published. Required fields are marked *