※ 강의를 듣고 제가 이해한 내용을 바탕으로 정리한 것이라서 오류가 있을 수 있습니다.
polished의 스타일 관련 유틸 함수 사용하기
Sass 를 사용 할 때에 lighten() 또는 darken() 과 같은 유틸 함수를 사용하여 색상에 변화를 줄 수 있었는데 styled-components 에서도 비슷한 유틸 함수를 사용하고 싶다면 polished 라는 라이브러리를 사용하면 된다.
설치: npm add polished
색상 코드를 지닌 변수를 Button.js 에서 선언을 하는 대신에 ThemeProvider 라는 기능을 사용하여 styled-components 로 만드는 모든 컴포넌트에서 조회하여 사용 할 수 있는 전역적인 값을 설정해보겠다.
App.js
import React from 'react'; import styled, { ThemeProvider } from 'styled-components'; // ThemeProvider를 사용하면 styled-components를 사용하는 모든 컴포넌트에서 색상을 지정할 수 있다. import Button from './components/Button'; const AppBlock = styled.div` width: 512px; margin: 0 auto; margin-top: 4rem; border: 1px solid black; padding: 1rem; `; const palette = { blue: '#228be6', gray: '#496057', pink: '#f06595' }; function App() { return ( <ThemeProvider theme={{palette}}> {/* ThemeProvider 사용 */} <AppBlock> <Button color="blue">BUTTON</Button> <Button color="pink">BUTTON</Button> <Button color="gray">BUTTON</Button> </AppBlock> </ThemeProvider> ); } export default App;
이렇게 App.js 에서 theme 을 설정하면 ThemeProvider 내부에 렌더링된 styled-components 로 만든 컴포넌트에서 palette 를 조회하여 사용 할 수 있다.
components/Button.js
import React from 'react'; import styled, { css } from 'styled-components'; import { darken, lighten } from 'polished'; // polished의 darken, lighten 함수 불러옴 const StyledButton = styled.button` /* 공통 스타일 */ display: inline-flex; outline: none; border: none; border-radius: 4px; color: white; font-weight:bold; cursor: pointer; padding-left: 1rem; padding-right: 1rem; /* 크기 */ height: 2.25rem; font-size: 1rem; /* 색상 */ ${props => { const color = props.theme.palette[props.color]; return css` background: ${color}; &:hover { background: ${lighten(0.1, color)}; } &:active { background: ${darken(0.1, color)}; } `; }} /* 버튼 간의 간격 */ & + &{ margin-left: 1rem; } `; function Button({ children, color, ...rest }) { return <StyledButton color={color} {...rest}>{children}</StyledButton>; } export default Button;
ThemeProvider 로 설정한 값은 styled-components 에서 props.theme 로 조회 할 수 있다.
실행 결과

'개발 공부한 내용 정리 > React' 카테고리의 다른 글
React- styled-components 버튼 outline, fullWidth (0) | 2020.10.12 |
---|---|
React- styled-components 버튼 사이즈 조정하기 (0) | 2020.10.11 |
React- styled-components로 버튼 만들기 (0) | 2020.10.09 |
React- styled-components (0) | 2020.10.08 |
React- CSS module (0) | 2020.10.07 |