kud.io/writing

Composition with styled-components or emotion

2019-11-03 · 1 min · engineering · design

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:

javascript
// MyElement.js
const MyElement = styled.div``

Alright, you want know to extend it.

javascript
// Base.js
const Base = styled.div``

// MyElement.js
const MyElement = styled(Base)``

Lovely.

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

The idea is to do that:

javascript
// base.js
const base = css``

// anotherBase.js
const anotherBase = css``

// MyElement.js
const MyElement = styled.div`
  ${base}
  ${anotherBase}
`

Boom! 💥

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

javascript
// base.js
const base = css``

// anotherBase.js
const anotherBase = css``

// MyElement.js
const MyElement = styled.div`
  ${base}

  ${({ active }) =>
    active &&
    css`
      ${anotherBase}
    `}
`

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!