Advanced ways to write styled-components

Jonas Antonelli
Ship It!
Published in
2 min readJul 19, 2021
Photo by Lucas Benjamin on Unsplash

Creating a component using styled-components is fascinating. Of course, with everything you learn, you need to practice becoming fast and productive. Every day, you can improve your techniques and discover ways to do the same thing.

Having these different ways in your repertoire is important when solving a specific context. It was this reason that made me write this article.

I will show you five ways to write a styled-components then you can decide what makes the most sense for your context.

Styled function with the shorthand tag name

The first way is using the styled helper method imported of styled-components package. You should use the shorthand tag name to define your HTML tag name.

Using the shorthand tag name 'ul'

Styled function wrapping a custom component

You will keep using the styled function, but now you will write a custom component instead of setting some specific tag name, then wrap that component using the styled function.

Note that is important to pass the rest parameter for the root element to allow the styled-components to insert the styles there.

Wrapping a custom component

Readable style + Custom component

Similar to the example above, but more readable by separating the style from the component

Readable styled-components

Extending from another component

You will declare a base for the list component and then create the UnorderedList component from the style generated in the base component.

Extending from another component

Referring to another component

In this example, you will create the item styled component and then the unordered list styled component. Within the unordered list style, you will refer to the item and add a spacing style.

Referring to another component

Switching the rendered element

You can change the component element at render time while preserving the styles

Switching the rendered element

If you prefer, you can use the attrs helper function to send the properties and customize your component at the same time, or send it as a prop to the component.

Switching and styling <ul> element to <ol>

All of these ways are used here at RD Station to style our Design System and layouts. If

If you are looking for a new job opportunity, become a part of our team! We are constantly on the lookout for great talent.

--

--