Styled components is the new rage in the world of React. It allows to define components with accompanying style like below.

The above code defines a Button component which is styled based on a link element. The style is defined in a template literal string. The template literal also has some code within it. So, how does it work really?

Tagged Template Literals

Most of us are familiar with template literals in JavaScript. Tagged template literals is another variation of how we can use template literals.

We want to take color in hexadecimal format and convert it to plain english string. To process template literals, we use tags in front of the template literal.

Using the tag in front of the template literal, we get the string, The color is red.

Styled components

Styled components take tagged template literals to a whole new level. It is possible to return any object from the tag function. For example, a tagged template literal can return an object instead of a string. For example, it is possible to convert a hexadecimal color string to a React component.

Use the component like so.

Styled components do a similar transformation. They take a CSS string with some code within it. The tag is based on a HTML element like h1 or a. It returns the corresponding React component with some CSS attached to it.

Styled components is a great example of tagged template literals in action.

Tagged template literals in Styled components
Tagged on: