_kud's tech blog

Composition with styled-components or emotion

When I use styled-components or emotion, it often happens that I want to extend more than only one component to another one. But I don't only want to extend, I also want to extend in certain situations directly via props. So I read lots of issues on styled-components' github page and I finally found a solution which I find great.

Imagine this:

1// MyElement.js
2const MyElement = styled.div``

Alright, you want know to extend it.

1// Base.js
2const Base = styled.div``
3
4// MyElement.js
5const MyElement = styled(Base)``

Lovely.

But now, you want to extend it by another one again. Ha! Tough right?

The idea is to do that:

1// base.js
2const base = css``
3
4// anotherBase.js
5const anotherBase = css``
6
7// MyElement.js
8const MyElement = styled.div`
9 ${base}
10 ${anotherBase}
11`

Boom! 💥

Bonus: you could use it depending on certains props like:

1// base.js
2const base = css``
3
4// anotherBase.js
5const anotherBase = css``
6
7// MyElement.js
8const MyElement = styled.div`
9 ${base}
10
11 ${({ active }) =>
12 active &&
13 css`
14 ${anotherBase}
15 `}
16`

That's great, right?!

If you have any other idea to extend it in a better way, feel free to contact me on Twitter. Thanks! Bye bye!