_kud's tech blog

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.js
2
3const Root = styled.div`
4 display: flex;
5 height: 100vh;
6 position: relative;
7 overflow: hidden;
8 background-color: #ffffff;
9`
10
11const Main = styled.div``
12const Aside = styled.div``
13
14class Layout extends React.Component {
15 render() {
16 const { children, aside } = this.props
17
18 return (
19 <Root>
20 <Main>{children}</Main>
21
22 {aside && <Aside>{aside}</Aside>}
23 </Root>
24 )
25 }
26}
27
28export default Layout
1// page.js
2
3const AnotherLayout = styled(Layout)`
4 background-color: #333;
5`
6
7class Page extends React.Component {
8 render() {
9 return <AnotherLayout>{"Hello!"}</AnotherLayout>
10 }
11}
12
13export 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.js
2
3class Layout extends React.Component {
4 render() {
5 const { className, children, aside } = this.props
6
7 return (
8 <Root className={className}>
9 {...}
10 </Root>
11 )
12 }
13}
14
15export default Layout

and now, it is fine! (works also on emotion). 🙏