- Sass
- styled-components
Sass
- css 전처리기
- 복잡한 작업을 쉽게 해주고, 스타일 코드의 재활용성, 가독성을 높여 유지보수의 용이함 확보
- https://heropy.blog/2018/01/31/sass/
styled-components
import React from 'react';
import styled, { css } from 'styled-components';
//tagged template literal 문법이용한 styled component
const Box = styled.div`
background: ${props => props.color || 'blue'};
padding: 1 rem;
display: flex;
`;
const Button = styled.button`
background: white;
color: black;
border-radius: 4px;
padding: 0.5rem;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
font-size: 1rem;
font-weight: 600;
/* &으로 자기자신 선택 */
&:hover {
background: black;
}
& + button {
margin-left: 1rem;
}
`;
const StyledComponent = () => {
return (
<Box color="black">
<Button>left</Button>
<Button>right</Button>
</Box>
);
};
export default StyledComponent;
- 자바스크립트파일 안에 스타일을 선언하는 'CSS-in-JS' 방식
- Tagged 템플릿 리터릴문법 문법을 통해 스타일을 전달하면, 해당 스타일이 적용된 리액트 컴포넌트가 생성
- 템플릿 리터럴 : 일반 문자열과 다르게 ` (backtick) 사이에 작성하며 ${ ...}를 삽입하여 객체나 함수를 전달할 수 있다
- Tagged 템플릿 리터럴 : 템플릿 리터럴 앞에 함수명이 있으면 해당 함수가 호출되고 템플릿 리터럴의 값이 함수에 전달되어 함수에서 템플릿 안의 값을 온전히 추출할 수 있다.
이를 tagged template literals 이라고 한다
// ...
const Button = styled.button`
/* ... */
${props =>
props.inverted &&
css`
background: none;
border: 2px solid white;
color: white;
&:hover {
background: white;
color: black;
}
`};
/* ... */
`;
//...
- props에 따른 조건부 스타일링
- css` ... ` 로 감싸주어서 tagged 템플릿 리터럴을 사용해 주어야 한다
//...
//tagged template literal 문법이용한 styled component
const Box = styled.div`
background: ${props => props.color || 'blue'};
padding: 1 rem;
display: flex;
width: 1024px;
margin: 0 auto;
@media (max-width: 1024px) {
width: 768px;
background: ${props => props.color || 'red'};
}
@media (max-width: 768px) {
width: 100%;
background: ${props => props.color || 'green'};
}
`;
//...
- 반응형 디자인1 : css에서 할때와 동일
const sizes = {
desktop: 1024,
tablet: 768
};
// 위에있는 size 객체에 따라 자동으로 media 쿼리 함수를 만든다
// 참고: https://www.styled-components.com/docs/advanced#media-templates
const media = Object.keys(sizes).reduce((acc, label) => {
acc[label] = (...args) => css`
@media (max-width: ${sizes[label] / 16}em) {
${css(...args)};
}
`;
return acc;
}, {});
const Box = styled.div`
/* props 로 넣어준 값을 직접 전달해줄 수 있습니다. */
background: ${props => props.color || 'blue'};
padding: 1rem;
display: flex;
width: 1024px;
margin: 0 auto;
${media.desktop`width: 768px;`}
${media.tablet`width: 768px;`};
`;
- 반응형디자인2 : styled-components에서 제공하는 유틸함수를 사용
'Javascript > React' 카테고리의 다른 글
#8-1 컴포넌트 최적화 (0) | 2020.02.17 |
---|---|
#8 React todo-app 1 (0) | 2020.02.17 |
#6 React Hooks (0) | 2020.02.14 |
#5 React Component Lifecycle (0) | 2020.02.13 |
#4 Component 반복 (0) | 2020.02.12 |