import React from 'react';
import ReactDOM from 'react-dom/client';
import { ThemeProvider } from 'styled-components';
import Router from './Router';
import GlobalStyle from './styles/GlobalStyle';
import theme from './styles/theme';
import variables from './styles/variables';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<ThemeProvider theme={{ style: theme, variables }}>
<GlobalStyle />
<Router />
</ThemeProvider>
);
아주 기본적이지만 몰라선 안되는 ThemeProvider에 대해 알았다.
ThemeProvider는 그안에 depth가 얼마나 되었든지 하위에 들어있는 component들에게 theme 속성을 전해줄 수 있다.
다만 이는 명백히 styledComponent에 한해서 이다.
import React from 'react';
import styled from 'styled-components';
import theme from '../../../styles/theme';
function NavForCreatorCenter(props) {
return (
<NavContainor>
<Title>Creator Center</Title>
<Icon />
</NavContainor>
);
}
const NavContainor = styled.nav`
background-color: ${props => props.theme.style.lightGrey};
height: 80px;
`;
const Title = props => {
console.log('props', props);
return <div>{props.children}</div>;
};
const Icon = styled.img.attrs({
src: `https://cdn-icons-png.flaticon.com/512/3282/3282468.png`,
})`
height: 100%;
`;
export default NavForCreatorCenter;
위의 코드에서 나는 Title에서 왜 props에 ThemeProvider에서 내려주는 props.theme 속성이 보이지 않을까 의문을 품었고 Router에서부터 props를 찍어가며 혹여 중간에 누락되는것인가도 확인해보았다.
하지만 이는 누락된것이 아니었다.
애초에 Title은 styledComponent가 아니기에 ThemeProvider로부터 속성을 상속받을 수 없었다.
import React from 'react';
import styled from 'styled-components';
import theme from '../../../styles/theme';
function NavForCreatorCenter(props) {
return (
<NavContainor>
<Title>Creator Center</Title>
<TitleForTest>TItle For Test</TitleForTest>
<Icon />
</NavContainor>
);
}
const NavContainor = styled.nav`
background-color: ${props => props.theme.style.lightGrey};
height: 80px;
`;
// const Title = styled.div`
// font-size: 20px;
// `;
const Title = props => {
console.log('props', props);
return <div>{props.children}</div>;
};
const TitleForTest = styled(Title)`
font-size: 40px;
`;
const Icon = styled.img.attrs({
src: `https://cdn-icons-png.flaticon.com/512/3282/3282468.png`,
})`
height: 100%;
`;
export default NavForCreatorCenter;
위와같이 TitleForTest는 Title을 상속받는 StyleComponent이다.
자, TitleForTest는 StyleComponent, Title은 그냥 React Component이다.
하여 콘솔창을통해 확인해본 결과
Title은 그냥 Children만이 있을뿐이고
TitleForTest에는 StyleComponenet로서 클래스명이 존재하는것이다.
이 클래스명을 통해 ThemeProvider로부터 속성을 상속받을 수 있는것이고 말이다.
관련된 수정 내용을 이 글에 추가적으로 작성하였습니다.