ThemeProvider는 React에서 styled-components를 이용하여 스타일을 관리할 때에 다크모드와 같은 테마 전환 기능을 쉽게 사용하기 위해 사용됩니다.
App.js
// JSX import { ThemeProvider } from 'styled-components'; const theme = { colors: { primary: '#0070f3', secondary: '#1db954', }, border: { main: '#101010', }, }; function App() { return ( <ThemeProvider theme={theme}> <Wrap /> </ThemeProvider> ); }
위와 같이 작성할 시 아래와 같이 Wrap 컴포넌트에서 theme객체를 참조할 수 있습니다.
Wrap.jsx
// JSX const Button = styled.button` background-color: ${({ theme }) => theme.colors.primary}; background-color: ${props => props.theme.colors.primary}; `; function Wrap(props) { ~~~ }
App.js
// JSX import { ThemeProvider } from 'styled-components'; import { light, dark } from './style/theme'; function App() { const [ isdark, setIsdark ] = useState(false); const DarkToggle = () => { if (isdark){ setIsdark(false); } else { setIsdark(true); } return( <ThemeProvider theme={isdark ? dark : light}> <Wrap /> </ThemeProvider> ); };
./style/theme.jsx
// JSX export const light = { isdark: false, colors: { primary: 'black', secondary: '#AAAAAA', }, border: { main: '#101010', }, }; export const dark = { isdark: true, colors: { primary: 'white', secondary: '#eeeeee', }, border: { main: '#C1C1C1', }, };
theme={isdark ? dark : light}>
ThemeProvider는 context 기능처럼 감싸진 컴포넌트 모두에서 객체에 접근 가능합니다.
다만, styled-components에서만 사용이 가능하며 아래와 같이 컴포넌트 작성 내부에서는 사용할 수 없습니다.
잘못된 사용 방법
// JSX function Wrap(props) { <Component className = {({ theme }) => theme.isdark ? 'dark' : 'light'} /> }