개발공부/개념정리 | CSS
Styled Components
개발집사
2022. 8. 26. 10:12
설치하기
# with npm
$ npm install --save styled-components
# with yarn
$ yarn add styled-components
packje.json에 아래 코드 추가하기.
{
"resolutions": {
"styled-components": "^5"
}
}
불러오기
import styled from "styled-components"
기본사용법
백틱 사용
//임포트를 해주고
import styled from "styled-components";
//컴포넌트를 만들고
//styled.태그종류
const MainButton = styled.button`
background-color: red;
color: white;
&:hover{
background: yellow;
transition: 0.5s;
}
`;
export default function App() {
return <MainButton>this is mainbutton!!</MainButton>
}
컴포넌트 재활용해서 새로운 컴포넌트 만들기
const 컴포넌트 이름 = styled(재활용할 컴포넌트)`
추가할 css속성: 속성값;
`
//AddMainButton에는 위에서 만든 MainButton의 css속성에 아래 속성들이 추가된다.
const AddMainButton = styled(MainButton)`
margin: 20px;
`
Props 활용하기
//리터럴 문법을 사용하여 js코드를 사용할 수 있다.
const 컴포넌트이름 = styled.태그종류`
css속성: ${(props)= 함수코드}
`;
//1. 조건부 렌더링
const Button = styled.button`
color: ${(props)=>props.blue ? "blue" : "red"}
`
//=>
<Button blue>Button1</Button> // blue색 버튼
<Button>Button2></Button> // red색 버튼
//2.props 값으로 렌더링
const Button = stled.button`
color: ${(props)=>props.color ? props.color : "red"}
`
전역 스타일 설정하기
import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
button {
padding : 10px;
margin : 5px;
border-radius : 2rem;
color: white;
background-color: black;
}
`
//GlobalStyle을 최상위 컴포넌트에서 사용!
function App() {
return (
<>
<GlobalStyle />
<Button>전역 스타일 적용하기</Button>
</>
);
}