React.js

[React] styled-component (Css-in-Js)

임호랑이 2023. 1. 11. 15:08

기존 css와는 다르게 컴포넌트생성과 동시에 css 를 작성한다.

괜히 Css-in-Js 가 아닌것같다..

styled-component 설치

npm i styled-component

 

상위.jsx

A : styledButton 이라는 컴포넌트를 만든후 컴포넌트 재사용

B : styledButton 컴포넌트에 props 를 내려서 사용

C : styledButton 컴포넌트에 styled-component 중첩 재사용

D : as 속성을 이용해서 엘리먼트 변경

E : as 속성을 이용해서 컴포넌트 중첩 변경

F : 컴포넌트 생성 + styled-component 사용한 컴포넌트를 styledButton 컴포넌트에 재사용 (props 조건부 추가)

 

 

StyledButton.jsx

props 를 이용할땐 이런식으로 이용가능

 

GlobalStyle 설정

styled-component 는 각 컴포넌트에 직접 style 을 준다.

만약 전역으로 css 을 주고싶으면 creacteGlobalStyle 을 이용해서

엘리먼트 혹은 클래스에 스타일을 준뒤 글로벌로 사용하고싶은 위치에 생성하면된다

 

Element attr 설정

a태그 컴포넌트에 .attrs 로 해당 엘리먼트에 추가하고싶은 어트리뷰트를 설정해줄수있다

 

응용 ) NavLink + active + styledComponent