반응형
VScode Extensions 소개
Styled Components를 사용할 때 템플릿 리터럴을 사용해서 작성하기 때문에 문자열로 인식된다.
즉, 자동완성이 지원되지 않기에 많이 불편하다.
위의 Extensions을 사용하면 CSS 파일에서 작성하는 것처럼 자동완성 기능을 지원해준다.
설치하기
# with npm
$ npm install --save styled-components@latest
# with yarn
$ yarn add styled-components
불러오기
// 전역 스타일
import { createGlobalStyle } from "styled-components";
// 지역 스타일
import styled from "styled-components"
반응형
문법
전역 스타일
전역 스타일을 설정하기 위해 createGlobalStyle 함수를 불러오고,
<GlobalStyle /> 컴포넌트를 최상위 컴포넌트에서 사용해 주면 된다.
// example
import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
button {
padding : 5px;
margin : 2px;
border-radius : 5px;
}
`
function App() {
return (
<>
<GlobalStyle />
<Button>전역 스타일 적용하기</Button>
</>
);
}
지역 스타일
따옴표( ' )가 아닌 백틱( ` )을 사용합니다!
// Styled Components 형식
import styled from "styled-components"
const 컴포넌트_이름 = styled.태그종류`
CSS속성1 : 속성값1;
CSS속성2 : 속성값2;
...
`;
const 컴포넌트_이름 = styled(재사용할_컴포넌트이름)`
추가할 CSS속성1 : 속성값1;
추가할 CSS속성2 : 속성값2;
...
`;
// example
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;
`;
Props
// Styled Components의 props 형식
const 컴포넌트_이름 = styled.태그종류`
CSS속성 : ${ (props) => 함수코드 }
`;
Props로 조건부 렌더링하기
// example1
// GlobalStyle이 설정되어 있다고 가정하겠습니다.
import styled from "styled-components";
import GlobalStyle from "./GlobalStyle";
const Button = styled.button`
background: ${(props) => (props.skyblue ? "skyblue" : "white")};
`;
function App() {
return (
<>
<GlobalStyle />
<Button skyblue>Button1</Button>
<Button>Button2</Button>
</>
);
}
Props 값으로 렌더링하기
// example2
// GlobalStyle이 설정되어 있다고 가정하겠습니다.
import styled from "styled-components";
import GlobalStyle from "./GlobalStyle";
const Button1 = styled.button`
background: ${(props) => (props.color ? props.color : "white")};
`;
function App() {
return (
<>
<GlobalStyle />
<Button1>Button1</Button1>
<Button1 color="orange">Button1</Button1>
<Button1 color="tomato">Button1</Button1>
</>
);
}
// example3
// GlobalStyle이 설정되어 있다고 가정하겠습니다.
import styled from "styled-components";
import GlobalStyle from "./GlobalStyle";
const Button2 = styled.button`
background: ${(props) => props.color || "white"};
`;
// background: ${(props) => (props.color ? props.color : "white")}; 와 같다.
function App() {
return (
<>
<GlobalStyle />
<Button2>Button2</Button2>
<Button2 color="pink">Button2</Button2>
<Button2 color="turquoise">Button2</Button2>
</>
);
}
Styled Components을 알아보는 시간이었습니다.
틀린 내용은 댓글로 알려주시면 감사하겠습니다.
반응형