Back to home

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:

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

Alright, you want know to extend it.

// 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:

// 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:

// 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!