리액트에서 스타일을 지정하는 방법
1) 인라인
2) css 파일 작성 후 import
3) CSS in JS
- JS로 CSS를 구현하는 것
- 조건에따라 스타일 적용하거나 로직을 적용하는 것이 가능해짐
- styled-component는 이를 위한 도구!
styled-component
1) yarn을 이용해 styled-components 설치
yarn add styled-components
2) vscode에서 확장 설치
3) 사용할 jsx 파일에서 import styled
import styled from "styled-components";
4) 스타일된 컴포넌트 만들기
const StyledBox = styled.div`
width: 100px;
height: 100px;
border: 1px solid red;
margin: 20px;
`;
5) 컴포넌트를 사용하던 방식대로 StyledBox 사용하기
function App() {
return <StyledBox>박스 확인</StyledBox>;
}
조건부 스타일링 만들어보기
const StyledBox = styled.div`
width: 100px;
height: 100px;
border: 1px solid ${(props) => props.borderColor};
margin: 20px;
`;
function App() {
return (
<>
<StyledBox borderColor="red">박스 확인</StyledBox>
<StyledBox borderColor="green">박스 확인</StyledBox>
<StyledBox borderColor="blue">박스 확인</StyledBox>
</>
);
}
props를 전달해주면 된다!
좀 더 개선된 방법
import styled from "styled-components";
const StyledBox = styled.div`
width: 100px;
height: 100px;
border: 1px solid ${(props) => props.borderColor};
margin: 20px;
`;
const boxList = ["red", "green", "blue"];
const getLabel = (color) => {
switch (color) {
case "red":
return "빨간박스";
case "green":
return "초록박스";
case "blue":
return "파란박스";
default:
return "검정박스";
}
};
function App() {
return (
<>
{boxList.map((boxColor) => {
return (
<StyledBox key={boxColor} borderColor={boxColor}>
{getLabel(boxColor)}
</StyledBox>
);
})}
</>
);
}
export default App;
전역(global) 스타일 지정하기
1) globalStyle을 담을 jsx 파일 생성
2) createGlobalStyle import
import { createGlobalStyle } from "styled-components";
3) 적용할 스타일 작성
import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
body {
color: red;
line-height: 1.5;
}
`;
export default GlobalStyle;
4) 적용할 곳에서 컴포넌트 사용
function App() {
return (
<>
<GlobalStyle />
{boxList.map((boxColor) => {
return (
<StyledBox key={boxColor} borderColor={boxColor}>
{getLabel(boxColor)}
</StyledBox>
);
})}
</>
);
}
reset.css 적용도 globalStyle로 적용할 수 있다!
'React' 카테고리의 다른 글
[React] useRef (0) | 2024.08.16 |
---|---|
[React] useState (0) | 2024.08.16 |
[React] 리액트의 개념과 성능 최적화 팁 (0) | 2024.08.14 |
[React] Rendering과 Virtual DOM (0) | 2024.08.08 |
[React] state (0) | 2024.08.08 |