
Extending your react component with styled-components
Yesterday, I was playing with styled-components and I wanted to change the style of my <Layout/>
component injected into another component for a specific case but I didn't understand why it didn't work when I extended it.
Imagine this:
1// layout.js23const Root = styled.div`4 display: flex;5 height: 100vh;6 position: relative;7 overflow: hidden;8 background-color: #ffffff;9`1011const Main = styled.div``12const Aside = styled.div``1314class Layout extends React.Component {15 render() {16 const { children, aside } = this.props1718 return (19 <Root>20 <Main>{children}</Main>2122 {aside && <Aside>{aside}</Aside>}23 </Root>24 )25 }26}2728export default Layout
1// page.js23const AnotherLayout = styled(Layout)`4 background-color: #333;5`67class Page extends React.Component {8 render() {9 return <AnotherLayout>{"Hello!"}</AnotherLayout>10 }11}1213export default Page
As you can see here, I extended my <Layout>
to change the property background-color
. However, when I did that, nothing happened and I was wondering why.
The reason is that you need to also transfer the className
. Ha!
The trick is here, in layout.js
, add the className
.
1// layout.js23class Layout extends React.Component {4 render() {5 const { className, children, aside } = this.props67 return (8 <Root className={className}>9 {...}10 </Root>11 )12 }13}1415export default Layout
and now, it is fine! (works also on emotion). 🙏