안녕하세요, 피터팬입니다!
오늘은 styled-component를 사용해볼 건데요!
React의 style요소를 css로 꾸밀 때, 보통 class를 사용합니다. className="button"이라고 하여 css에 연결합니다. 그런데, 다른 component에도 button이라는 class가 있다면 해당 component에도 의도치 않게 적용이됩니다.
이러한 문제를 해결하기 위해 사용하는 것이 styled-component인데요! 사이트는 다음과 같습니다.
사이트
https://styled-components.com/
styled-components
Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅🏾
styled-components.com
다운로드
npm install --save styled-components
위 코드를 터미널에 입력해 install해주면 됩니다.
적용법
import styled from 'styled-components'
사용법
사용법은 매우 간단합니다! component와 약간은 차이가 있습니다.
const Button = { return ( ) }했던 Component대신에 아래와 같은 식을 작성해주면 됩니다.
Const (변수명) = styled.(요소유형)`(스타일 작성)`
const Button = styled.button`
background: transparent;
border-radius: 3px;
border: 2px solid palevioletred;
color: palevioletred;
`
export default Button;
그리고, export한 Button을 Component명 처럼 사용하면 됩니다.
이 또한 Component이기에, props를 전달해 사용할 수 있습니다.
예시
# 부모 Component
import {useState} from 'react'
const App = () => {
const [isvalid,setIsvalid] = useState(false);
return(
<Form invalid = {isValid}>
<label>Hello</label>
<input />
</From>
<button onClick={()=>{setIsValid(true)}}>Click</button>
)
}
export default App;
# 자식 Component
import styled from 'styled-components';
const Form = styled.div`
width:100px;
& label{
font-wieght:bold;
border:1px solid ${(props) => (props.invalid ? "red":"#ccc")}
}
&:focus{
background:red;
}
`
위 처럼 부모 component에서는 props로 전달하여, 자식 component에서는 ${} 내부에, props를 매게변수로 받아 사용하면 됩니다.
위처럼 작성하면 작성한 스타일이 적용된 요소가 만들어집니다. 그리고 class명은 새로고침할 때마다 변경되며, 아래와 같이 class명이 랜덤생성됩니다.
'WebProgramming > React' 카테고리의 다른 글
[React] useReducer를 이용한 상태관리 (0) | 2022.07.22 |
---|---|
[React] useRef로 input 상태 관리하기 (0) | 2022.07.21 |
[React] Createportal을 이용해 특정 요소에 하위 요소 추가하기 (0) | 2022.07.21 |
[React] CSS Module을 이용한 컴포넌트 스타일링 (0) | 2022.07.20 |
[React] Checkbox 값 제어하기 (0) | 2022.07.17 |
[React] 한 페이지 정리 (0) | 2022.07.17 |
[React] Component로 css요소 복사하기 (0) | 2022.07.17 |
[React] 웹사이트 배포하기 (0) | 2022.07.13 |