TIL-40 React Styled Components ๐Ÿ’…

6659 ๋‹จ์–ด styled componentReactReact

์™œ Styled Components๋ฅผ ์จ์•ผํ• ๊นŒ?

  • CSS ํด๋ž˜์Šค ๋ช…์— ๋Œ€ํ•œ ๊ณ ๋ฏผ์€ ์—ฌ์ „ํ•˜๋‹ค.
    • ex. BEM (.block__element--modifier, button button--state-success)
  • ์ •ํ•ด์ง„ ๊ฐ€์ด๋“œ๊ฐ€ ์—†์œผ๋ฉด ๊ตฌ์กฐ๊ฐ€ ๋ณต์žกํ•ด์ง„๋‹ค.
  • ๋ฐฉ๋Œ€ํ•œ ์Šคํƒ€์ผ ์ •๋ณด๋กœ ์ธํ•œ ์Šคํฌ๋กค ์ง€์˜ฅ๋„ ์กด์žฌ
  • ์—ฌ์ „ํžˆ CSS ํด๋ž˜์Šค๋กœ ์กฐ๊ฑด๋ถ€ ์Šคํƒ€์ผ๋ง์„ ํ•˜๊ณ  ์žˆ๋‹ค.
  • CSS ํด๋ž˜์Šค๋กœ ์กฐ๊ฑด๋ถ€ ์Šคํƒ€์ผ๋ง์„ ํ•˜๋”๋ผ๋„ ๋™์ ์ธ ๋ณ€ํ™”๋ฅผ ํ‘œํ˜„ํ•˜๊ธฐ์— ํ•œ๊ณ„๊ฐ€ ์žˆ๋‹ค
    - ex. 1์ดˆ์— px ๊ฐ’์„ 1์”ฉ ์ฆ๊ฐ€ โ†’ Inline ์Šคํƒ€์ผ์— ์˜์กด
    render(
    <div>
      <Button>Normal</Button>
      <Button width="100">Primary</Button>
    </div>
    );
    // ๋งŒ์•ฝ Button ์ปดํฌ๋„ŒํŠธ์— ์ „๋‹ฌ๋œ props(width)๊ฐ€ 200 ๋ฏธ๋งŒ(์กฐ๊ฑด)์ด๋ฉด
    // ์‚ผํ•ญ์—ฐ์‚ฐ์ž true : "palevioletred"
    // ์‚ผํ•ญ์—ฐ์‚ฐ์ž false : "white"
    const Button = styled.button`
    background: ${props => props.width < 200 ? "palevioletred" : "white"};
    color: ${props => props.primary ? "white" : "palevioletred"};
    font-size: 1em;
    margin: 1em;
    padding: 0.25em 1em;
    border: 2px solid palevioletred;
    border-radius: 3px;
    `;

# Nesting


```js

render(
  <>
    <Thing>Hello world!</Thing>
    <Thing>How ya doing?</Thing>
    <Thing className="something">
			<span className="contents">The sun is shining...<span>
		</Thing>
    <div>Pretty nice day today.</div>
    <Thing>Don't you think?</Thing>
    <div className="something-else">
      <Thing>Splendid.</Thing>
    </div>
  </>
)

const Thing = styled.div`
  color: blue;

  &:hover {
    color: red;
  }

  #id {
		div {
	    background: orange;
		}
  }

  .something-else & {
    border: 1px solid;
  }
`

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ