ㅇㅇㅈ Blog

프론트엔드 수행중

0%

Styled-component 사용해보기

CSS in JS

➡️ CSS in JS란 말 그대로 .css파일이 아닌 자바스크립트 안에 CSS를 정의하는 것

https://ko.reactjs.org/docs/faq-styling.html#what-is-css-in-js

why?

  • 모든 스타일이 Global에 선언되어 중복되지 않는 이름을 적용해야 하는 문제
  • css에서 에러를 감지하기가 어렵기 때문에
  • 사용하지 않는 코드 관리
  • vue같은 scope설정으로 컴포넌트내에서 css를 관리하는게 용이하지만 리액트는 그러지 못한다..

styled-components 설치

1
2
3
$ yarn add styled-components

$ npm i styled-components
1
2
3
4
5
"dependencies": {
"react": "^18.0.0",
"react-dom": "^18.0.0",
"styled-components": "^5.3.5"
},

기본 문법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import styled from 'styled-components';

const Title = styled.h1`
text-align: center;
color: palevioletred;
`;

const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;

function App() {
return (
<Wrapper>
<Title>Hello world</Title>
</Wrapper>
);
}

컴포넌트 생성하는것처럼 이름을 정의하고 styled.element`` 로 요소를 만들고 back quote 안쪽에 일반 css처럼 스타일을 정의해 준다
그리고 진짜 컴포넌트처럼 사용해주면 된다.

클래스이름이 자동 생성 되어있다

props

props 전달을 통해 스타일을 정의 할 수 도 있다
js이기 때문에 리터럴보간법으로 작성 할 수 있다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

const Title = styled.h1`
text-align: center;
color: palevioletred;
`;

const Wrapper = styled.section`
padding: 4em;
background-color: ${(props) => (props.primary ? 'royalblue' : 'papayawhip')};
`;

function App() {
return (
<Wrapper primary>
<Title>Hello world</Title>
</Wrapper>
);
}

스타일 확장

기존의 요소에서 스타일을 상속받고 새로운 것만 추가해 새롭게 만들 수 있다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

const Button = styled.button`
color: palevioletred;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;

const TomatoButton = styled(Button)` // 기존 버튼을 상속받을때
color: tomato;
border-color: tomato;
background-color: royalblue;
`;


function App() {
return (
<Wrapper>
<Button>Normal Button</Button>
<TomatoButton>Tomato Button</TomatoButton>
</Wrapper>
);
}
1
2
3
4
5
6
7
8
9
10
11
function App() {
return (
<Wrapper>
<Title>Hello world</Title>
<Button as='a' href='#'>
Normal Link Button
</Button>
<TomatoButton>Tomato Button</TomatoButton>
</Wrapper>
);
}

이런식으로 요소의 속성을 바꿔줄 수도 있다