Styled Components

๋…ธ๋งˆ๋“œ์ฝ”๋” - React JS ๋งˆ์Šคํ„ฐ ํด๋ž˜์Šค https://styled-components.com/

Install

  • CRA ํ›„์—

  • npm i styled-components

Using

1. import

import styled from "styled-components";

2. Create styled components

  • ๋ฐฑํ‹ฑ ์‚ฌ์ด์—๋Š” css๊ฐ€ ๋“ค์–ด๊ฐ

  • vscode ์ต์Šคํ…์…˜ ์„ค์น˜ํ•˜๋ฉด ์ž๋™์™„์„ฑ

  • ํด๋ž˜์Šค ๋„ค์ž„์€ ๋žœ๋คํ•˜๊ฒŒ ์ง€์ •๋จ

const Father = styled.div`
  display: flex;
`;

const Btn = styled.button`
  color: white;
  background-color: tomato;
  border: 0;
  border-radius: 15px;
`;
}

3. Adapting and Extending

  • adapting(modify)

  • props ์‚ฌ์šฉ ๊ฐ€๋Šฅ

const Box = styled.div`
  background-color: ${(props) => props.bgColor}
`;

...์ค‘๋žต

  <Box bgColor="tomato" />
  • extending

  • styled(๊ธฐ์กด์ปดํฌ๋„ŒํŠธ)

  • ๊ธฐ์กด ์ปดํฌ๋„ŒํŠธ์˜ ๋ชจ๋“  ์†์„ฑ์— ์ƒˆ๋กœ์šด ์†์„ฑ์„ ๋” ํ•ด์คŒ

const Circle = styled(Box)`
  border-radius: 50px;
`;

...์ค‘๋žต

<Circle bgColor="teal" />

4. 'As' and Attrs

  • as๋ผ๋Š” props๋ฅผ ์ด์šฉํ•˜๋ฉด ์ •์˜๋œ ์Šคํƒ€์ผ์„ ๊ทธ๋Œ€๋กœ ๊ฐ€์ง€๊ณ  ๊ฐ€๋˜ ํƒœ๊ทธ๋„ค์ž„์„ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์Œ

const Btn = styled.button`
  color: white;
  background-color: tomato;
  border: 0;
  border-radius: 15px;
`;

...์ค‘๋žต

  <Btn>Log In</Btn>
  <Btn as="a" href="#">
    Link
  </Btn>
  • attrs ๋ฅผ ์ด์šฉํ•˜๋ฉด html์˜ ์†์„ฑ์„ ๋ฏธ๋ฆฌ ์„ค์ •ํ•  ์ˆ˜ ์žˆ์Œ

  • ์—ฌ๋Ÿฌ๊ฐœ์— ๋™์ผํ•œ ์„ค์ •์ด ํ•„์š”ํ•  ๊ฒฝ์šฐ ์œ ์šฉ

const Input = styled.input.attrs({ required: true, minLength: 10 })`
  background-color: tomato;
`;

5. Animations and Pseudo Selectors

  • animations

  • keyframes๋ผ๋Š” ํ—ฌํผ ํ•จ์ˆ˜๋ฅผ ์ถ”๊ฐ€

  • ๋ฐ–์—์„œ animation์„ ์„ ์–ธํ•˜๊ณ  styled-components์•ˆ์—์„œ ์‚ฌ์šฉ

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

const rotate = keyframes`
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
`;

const Box = styled.div`
  width: 200px;
  height: 200px;
  background-color: tomato;
  animation: ${rotate} 1s linear infinite;
`;
  • seudo Selectors

  • styled-components๊ฐ€ ์•„๋‹ˆ๋”๋ผ๋„ ์ปดํฌ๋„ŒํŠธ ๋‚ด์—์„œ ํ•˜์œ„ ํƒœ๊ทธ์— ๋Œ€ํ•œ ํƒ€๊ฒŸ ์„ ํƒ ๊ฐ€๋Šฅ

  • ์ถ•์•ฝ์–ด &

  • case1

const Box = styled.div`
  ...์ค‘๋žต
  span {
    font-size: 36px;
    &:hover {
      font-size: 40px;
    }
  }
`;

...์ค‘๋žต

  <Box>
    <span>๐Ÿค—</span>
  </Box>
  • styled-components ๋‚ด์—์„œ ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ์— ๋Œ€ํ•œ ํƒ€๊ฒŸ ์„ ํƒ ๊ฐ€๋Šฅ(๋ณ€์ˆ˜๋ช…์ฒ˜๋Ÿผ ์‚ฌ์šฉ)

  • case2

const Emoji = styled.span`
  font-size: 36px;
`;

const Box = styled.div`
  ...์ค‘๋žต
  ${Emoji}:hover {
      font-size: 98px;
  }
`;

...์ค‘๋žต

  <Box>
    <Emoji as="p">๐Ÿค—</Emoji>
  </Box>

Themes

  • ๋ชจ๋“  ์ƒ‰์ƒ์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” object

  • index.js์—์„œ ์„ค์ •ํ•˜๊ณ  App.js์—์„œ props๋กœ ๊ฐ€์ ธ๋‹ค ์”€

  • ์™„์ „ ์ฟจํ•จ๐Ÿคฉ

Last updated