React | Styled Component

앙두·2023년 1월 18일
0

React

목록 보기
12/20

리또컴(리액트 또 컴포넌트) 😡

Styled 자체가 함수고, React 컴포넌트를 반환한다.

Styled Component 를 사용하기 위해서는 먼저 패키지를 install 해주어야 한다.

$ npm install styled-component

설치 후, 당연히 역시나 import를 해주어야 한다.

import styled from "styled-components";

import를 해주었다면, Styled Component 를 만들어야 겠죠?
구조는 간단하다.

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

1. 태그명으로 쓸 변수명을 정해준다.
2. 변수명의 첫 글자는 대문자로 ! ( styled COMPONENT 니까 )
3. styled.[태그명] 을 쓰고 백틱을 사용!
4. 그 안에, 스타일 속성을 주면 된다!

<MyButton>버튼</MyButton>

jsx 부분에는 이렇게 적용시킨다.

💻 기본문법

고정 스타일링

import styled from "styled-components";

const MyButton = styled.button`
	color: white;
`

-> HTML 태그를 스타일링 할 때는, 태그명에 접근
개발자도구를 열어보면, 해당 태그에 component가 자동으로 생성해준 클래스 이름이 적용돼있다.

가변 스타일링

import styled from "styled-components";

const MyButton = styled(YourButton)`
	color: ${(props) => props.color ? "white" : "black" }
    background-color: ${(props) => props.background ? "white" : "black" }
    
function YourButton({ children, color, background }) {
  return (
    <MyButton color={color} background={background} Î>
      {children}
    </MyButton>
  );
}
`

-> React 컴포넌트를 스타일링 할 때는, 컴포넌트 import 후 인자로 넣어 접근
React 컴포넌트에서 전달해준 props 를 사용하여 스타일을 적용시킬 수 있다.

Primary를 사용하여 Boolean 조건으로 사용해도 된다.

import styled from "styled-components";

const MyButton = styled(YourButton)`
	color: ${(props) => props.primary ? "white" : "black" }
    background-color: ${(props) => props.primary ? "white" : "black" }
    
function YourButton({ children, color, background }) {
  return (
    <MyButton primary >
      {children}
    </MyButton>
  );
}
profile
쓸모있는 기술자

0개의 댓글