프론트엔드/React
[React] styled-components에 대해서 알아보자
병걸
2024. 1. 19. 15:07
styled-components는 무엇일까?
- 기존 돔을 만드는 방식인 css, scss 파일을 밖에 두고, 태그나 id, class이름으로 가져와 쓰지 않고, 동일한 컴포넌트에서 컴포넌트 이름을 쓰듯 스타일을 지정하는 것을 styled-components라고 합니다.
https://styled-components.com/
styled-components
CSS for the <Component> Age
styled-components.com
먼저 styled-components를 사용하기 위해서 환경설정을 해주어야 합니다.
npm install styled-components
환경설정이 문제 없이 진행되었으면,
import styled from "styled-components";
let YellowBtn = styled.button`
background : yellow;
color : black;
padding : 10px;
`
<YellowBtn>버튼</YellowBtn>
사용하고 싶은 컴포넌트 파일 내에 import를 해주고 원하는 변수명을 주어 원하는 위치에 사용하면 됩니다.

또한, 스타일이 비슷한 버튼을 구성할때는 props를 활용하여 재활용이 가능합니다.
import styled from "styled-components";
let YellowBtn = styled.button`
background : ${ props => props.bg };
color : black;
padding : 10px;
`
<YellowBtn bg="yellow">버튼</YellowBtn>
<YellowBtn bg="blue">버튼</YellowBtn>
이와 같이 원하는 색상으로 각기 다르게 사용할 수 있습니다.
styled-components 의 장점
1. CSS 파일을 오픈할 필요없이 JS 파일에서 바로 스타일을 넣을 수 있습니다.
2. 컴포넌트 내에 적은 style이 다른 JS 파일에 적용되지 않습니다.
3. 컴포넌트 내에 적으면 <style></style>로 넣어주어 페이지 로딩시간을 향상시켜줍니다.