React (2) styled-components

이건선·2023년 6월 6일

알아볼것

목록 보기
8/13

styled-components는 JavaScript 프레임워크인 React에서 CSS를 다루기 위한 도구 중 하나입니다. styled-components를 사용하면 컴포넌트에 스타일을 적용하는 코드를 깔끔하게 유지하면서, 리액트 컴포넌트의 재사용성과 조합성을 유지할 수 있습니다.


1. 기본 사용법:

다음과 같이 기본적인 스타일을 적용하는 컴포넌트를 만들 수 있습니다.

import styled from 'styled-components';

const StyledDiv = styled.div`
  width: 100px;
  height: 100px;
  background-color: blue;
`;

function App() {
  return <StyledDiv />;
}

export default App;

2. Props를 통한 스타일링:

styled-components는 JavaScript 템플릿 리터럴을 사용하기 때문에, props를 통해 컴포넌트의 스타일을 동적으로 바꾸는 것이 가능합니다.

const StyledDiv = styled.div`
  background-color: ${(props) => props.bgColor || 'blue'};
`;

function App() {
  return <StyledDiv bgColor="red" />;
}

3. 확장과 상속:

만약 공통적인 스타일이 있고 일부만 변경하고 싶다면, styled-components를 확장해서 사용할 수 있습니다.

const BaseButton = styled.button`
  padding: 10px 15px;
  border-radius: 3px;
`;

const PrimaryButton = styled(BaseButton)`
  background-color: blue;
  color: white;
`;

const SecondaryButton = styled(BaseButton)`
  background-color: gray;
  color: black;
`;

function App() {
  return (
    <>
      <PrimaryButton>Primary</PrimaryButton>
      <SecondaryButton>Secondary</SecondaryButton>
    </>
  );
}

4. 글로벌 스타일:

styled-components는 전체 애플리케이션에 적용될 글로벌 스타일을 정의하는 데도 사용할 수 있습니다.

import { createGlobalStyle } from 'styled-components';

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

function App() {
  return (
    <>
      <GlobalStyle />
      {/* other components */}
    </>
  );
}

5. 테마:

styled-components는 테마를 지원하므로, 애플리케이션의 전반적인 색상 팔레트나 폰트 등을 쉽게 변경할 수 있습니다.

import { ThemeProvider } from 'styled-components';

const theme = {


  primaryColor: 'blue',
  secondaryColor: 'gray',
};

const ThemedButton = styled.button`
  background-color: ${(props) => props.theme.primaryColor};
  color: white;
`;

function App() {
  return (
    <ThemeProvider theme={theme}>
      <ThemedButton>Themed</ThemedButton>
    </ThemeProvider>
  );
}

6. 애니메이션 (Animations):

styled-components에서 CSS 애니메이션을 사용하려면, keyframes 도구를 사용해야 합니다. keyframes를 사용하여 애니메이션 시퀀스를 생성한 후, 이를 원하는 스타일드 컴포넌트에 적용할 수 있습니다.

import styled, { keyframes } from 'styled-components';

// 애니메이션 생성
const rotate = keyframes`
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
`;

// 애니메이션 적용
const RotatingBox = styled.div`
  width: 100px;
  height: 100px;
  animation: ${rotate} 2s linear infinite;
`;

function App() {
  return <RotatingBox />;
}

7. 미디어 쿼리 (Media Queries):

styled-components에서 미디어 쿼리를 사용하여 반응형 디자인을 구현할 수 있습니다.

const ResponsiveDiv = styled.div`
  width: 100%;
  height: 100px;
  background-color: blue;

  // 미디어 쿼리
  @media (max-width: 600px) {
    background-color: red;
  }
`;

function App() {
  return <ResponsiveDiv />;
}

위 코드는 브라우저 창의 너비가 600px 이하일 때, div의 배경색을 빨간색으로 변경합니다.

8. keyframes:

keyframes 도구를 사용하면, @keyframes CSS 규칙을 JavaScript에서 만들 수 있습니다. 이렇게 만든 규칙은 애니메이션의 중간 상태를 지정하는 데 사용할 수 있습니다.

import styled, { keyframes } from 'styled-components';

// Keyframes 생성
const fadeIn = keyframes`
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
`;

// Keyframes 적용
const FadeInBox = styled.div`
  width: 100px;
  height: 100px;
  animation: ${fadeIn} 2s ease-in-out;
`;

function App() {
  return <FadeInBox />;
}

Hover 상태 스타일링:

const Button = styled.button`
  background-color: blue;
  color: white;

  &:hover {
    background-color: red;
  }
`;

위의 코드에서 &:hover는 버튼이 hover 상태일 때 스타일을 지정합니다.

Active 상태 스타일링:

const Button = styled.button`
  background-color: blue;
  color: white;

  &:active {
    background-color: green;
  }
`;

위의 코드에서 &:active는 버튼이 클릭되어 있는 동안 스타일을 지정합니다.

자식 선택자 스타일링:

const List = styled.ul`
  list-style: none;

  & > li {
    margin-bottom: 10px;
  }
`;

위의 코드에서 & > liul의 직접적인 자식인 li 태그에 스타일을 지정합니다.

CSS에서는 다양한 유형의 프로퍼티(또는 선택자)가 사용됩니다. &:와 함께 사용되는 몇 가지 주요 선택자는 다음과 같습니다:

  • :hover: 요소에 마우스를 올렸을 때 적용됩니다.
  • :active: 요소가 활성화되었을 때 적용됩니다 (예: 마우스로 클릭하고 있는 동안).
  • :focus: 요소가 포커스를 받았을 때 적용됩니다 (예: 키보드 탭으로 선택한 경우).
  • ::before / ::after: 요소의 내용 앞이나 뒤에 콘텐츠를 삽입합니다. 이는 주로 장식적인 목적으로 사용됩니다.
  • :first-child / :last-child: 자식 요소 중 첫 번째 또는 마지막 요소에 스타일을 적용합니다.
  • :nth-child(n): 자식 요소 중 n번째 요소에 스타일을 적용합니다.

이러한 프로퍼티는 &: 뒤에 붙여서 사용할 수 있습니다.

profile
멋지게 기록하자

0개의 댓글