Theming styled-components and creating styling add-ons.

Elegant way to markup theme-able properties in your styles.

Vlad Zhabinsky
2 min readFeb 7, 2020

Github NPM

  1. We are going to theme your styled-components like this:
import styledProps from 'styled-addons'const Button = styledProps ('button')`
font-size: 15px;
color: $theme.color;
background: $theme.background;
`;
export default Button;

2. We will learn how to build custom parser logic for your styled-components with styled-addons.

Docs

Add to your project styled-addons/readme.md.

How does styledProps work?

Treat it just like you treat styled-components default export. It will work the same except it will substitute all variables will resolver functions:

Essentially it will transform this:

styledProps(...)`
color: $theme.abc;`

Into this:

styledProps(...)`
color: ${props => props.theme.abc}`

Why use styled-addons?

It allows you to extend styled-components with your custom parsing logic.

The example above is an illustration of how you can create custom parsing logic for styled-components arguments.
Give it instructions to intercept certain pattern in tagged literals (regex) and define what those patterns should be substituted with (replace function).

Other similar libraries

I was truly surprised to see other projects claiming to make it easier to adopt themes with styled-components, but not making it in a way styled-addons does.

Some examples of solutions that are solving a similar problem, but are still walking on-the-surface include:

  1. styled-tools
    Extremely useful set of selectors functions. Creator did a great job.
    However, it might be more elegant to create an addon with styled-addons and have that logic hidden inside addon. Allowing you to avoid importing same helper functions again and again.
  2. styled-themer
    Same functionality, but arguably more boilerplate code compared to styled-addons.

Explore and challenge the way you write code as there might be patterns you use that are not entirely fitting your needs.

What is your preferred styling solution ?

Github NPM

Visit zhabinsky.com for more of my projects and articles.

--

--