본문 바로가기

CSS

styled-components의 특징 및 사용법

styled-components는 리액트의 css 스타일링 라이브러리이며, props를 활용하여 기능별로 스타일 적용이 가능하기 때문에 개인적으로 유용하게 잘 사용하고 있다.

 

특징

1. CSS in JS

자바스크립트 파일 내에서 css를 작성하기 때문에 리액트 컴포넌트 별로 스타일링하기 편하다

2. 컴포넌트에 기반한 스타일링

컴포넌트 별로 스타일링 유지보수하기 편하다

3. props

리액트의 기능인 props를 활용하여 상태변화에 따른 스타일링 적용을 유용히 사용 가능하다

 

사용법

라이브러리를 설치한다.

npm install styled-components
# or
yarn add styled-components

 

타입스크립트 사용 시, 추가적으로 설치해 준다.

npm i @types/styled-components
# or
yarn add @types/styled-components

 

간단히 컴포넌트로 스타일을 적용해 보자면 아래와 같다.

import React from 'react';
import { styled } from 'styled-components';

const App = () => {
    return (
        <AppContainer>
            <Button>클릭!</Button>
        </AppContainer>
    )
}

const AppContainer = styled.div`
    background-color: skyblue;
    padding: 50px;
`;
const Button = styled.button`
    color: green;
    width: 50px;
    heoght: 30px;
    cursor: pointer;
`;

export default App;

 

props 활용 시 다음과 같이 작성할 수 있다.

import React, { useState } from 'react';
import { styled } from 'styled-components';

const App = () => {
    const [toggle, setToggle] = useState<boolean>(false);
    const handleToggle = () => {
    	setToggle(!toggle);
    }
    
    return (
        <AppContainer toggle={toggle}>
            <Button onClick={handleToggle}>클릭!</Button>
        </AppContainer>
    )
}

const AppContainer = styled.div`
    /* props 기능 사용하기 */
    background-color: ${props => props.toggle ? 'pink' : 'skyblue'};
    padding: 50px;
`;
const Button = styled.button`
    color: green;
    width: 50px;
    heoght: 30px;
    cursor: pointer;
`;

export default App;

 

또한 전역적으로 스타일을 관리할 수 있는 기능(createGlobalStyle) 또한 제공된다

/* index.tsx */
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { createGlobalStyle } from 'styled-components';

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);

const GlobalStyle = createGlobalStyle`
  * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      border: 0;
      outline: 0;
      list-style: none;
    }
    button {
      background: transparent;
      cursor: pointer;
    }
`;

root.render(
  <React.StrictMode>
    <GlobalStyle />
    <App />
  </React.StrictMode>
);

reportWebVitals();

이런 식으로 전역적으로 스타일을 주거나 초기화시킬 수 있디.

'CSS' 카테고리의 다른 글

Next.js에서 Tailwindcss 사용해보기  (0) 2024.05.09