Styled Components

이유정·2022년 11월 14일
0

코드스테이츠 TIL

목록 보기
44/62

css 코드를 다룰 때 불편했던 점
1. class, id 이름 짓느라 고민
2. css 파일 안에서 내가 원하는 부분 찾기 어려움
3. css 파일이 너무 길어져서 쪼개고 싶음
4. 스타일 속성이 겹침
=> css를 컴포넌트화!
=> react 환경에서 사용 가능한 Styled Components!! 라이브러리

설치

npm install --save styled-components 

pakage.json 에 코드 추가

{
  "resolutions": {
    "styled-components": "^5"
  }
}

파일로 불러와준다

import styled from "styled-components"

01. 컴포넌트 만들기

import styled from "styled-components";

//Styled Components로 컴포넌트를 만들고
const BlueButton = styled.button`
  background-color: blue;
  color: white;
`;

export default function App() {
  // React 컴포넌트를 사용하듯이 사용하면 됩니다.
  return <BlueButton>Blue Button</BlueButton>;
}

02. 컴포넌트를 재활용해서 새로운 컴포넌트 만들기

import styled from "styled-components";

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

//만들어진 컴포넌트를 재활용해 컴포넌트를 만들 수 있습니다.
const BigBlueButton = styled(BlueButton)`
  padding: 10px;
  margin-top: 10px;
`;

//재활용한 컴포넌트를 재활용할 수도 있습니다.
const BigRedButton = styled(BigBlueButton)`
  background-color: red;
`;

export default function App() {
  return (
    <>
      <BlueButton>Blue Button</BlueButton>
      <br />
      <BigBlueButton>Big Blue Button</BigBlueButton>
      <br />
      <BigRedButton>Big Red Button</BigRedButton>
    </>
  );
}

03-1 props로 조건부 렌더링하기

import styled from "styled-components";
import GlobalStyle from "./GlobalStyle";
//받아온 prop에 따라 조건부 렌더링이 가능합니다.
const Button1 = styled.button`
  background: ${(props) => (props.skyblue ? "skyblue" : "white")};
`;

export default function App() {
  return (
    <>
      <GlobalStyle />
      <Button1>Button1</Button1>
      <Button1 skyblue>Button1</Button1>
    </>
  );
}

03-2 props 값으로 렌더링하기

import styled from "styled-components";
import GlobalStyle from "./GlobalStyle";

//받아온 prop 값을 그대로 이용해 렌더링할 수도 있습니다
const Button1 = styled.button`
  background: ${(props) => (props.color ? props.color : "white")};
`;
//다음과 같은 형식으로도 활용할 수 있습니다.
const Button2 = styled.button`
  background: ${(props) => props.color || "white"};
`;

export default function App() {
  return (
    <>
      <GlobalStyle />
      <Button1>Button1</Button1>
      <Button1 color="orange">Button1</Button1>
      <Button1 color="tomato">Button1</Button1>
      <br />
      <Button2>Button2</Button2>
      <Button2 color="pink">Button2</Button2>
      <Button2 color="turquoise">Button2</Button2>
    </>
  );
}

04. 전역 스타일 설정하기

import { createGlobalStyle } from "styled-components";

const GlobalStyle = createGlobalStyle`
	button {
		padding : 5px;
    margin : 2px;
    border-radius : 5px;
	}
`

이 GlobalStyle 컴포넌트를 최상위 컴포넌트에서 사용하면 전역에 스타일 적용된다.

function App() {
	return (
		<>
			<GlobalStyle />
			<Button>전역 스타일 적용하기</Button>
		</>
	);
}
profile
팀에 기여하고, 개발자 생태계에 기여하는 엔지니어로

0개의 댓글