Tagged template literals in Styled components

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

const Button = styled.a`
  display: inline-block;
  border-radius: 3px;
  padding: 0.5rem 0;
  margin: 0.5rem 1rem;
  width: 11rem;
  background: transparent;
  color: white;
  border: 2px solid white;
`

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.

const color = '#f00';
const colorStatement = colorString`The color is ${color}`;

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.

function colorString(strings, colorHex) {
  let colorStr;
  switch(colorHex) {
    case '#fff':
      colorStr = 'white'
      break;
    case '#000':
      colorStr = 'black;
      break;
    case '#f00':
       colorStr = 'red';
       break;
     case '#0f0':
       colorStr = 'green';
       break;
     case '#00f':
       colorStr = 'blue';
       break;
  }

   return strings[0] + colorStr;
}

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.

function colorComp(strings, colorHex) {
  let colorStr;
  switch(colorHex) {
    case '#fff':
      colorStr = 'white'
      break;
    case '#000':
      colorStr = 'black;
      break;
    case '#f00':
       colorStr = 'red';
       break;
     case '#0f0':
       colorStr = 'green';
       break;
     case '#00f':
       colorStr = 'blue';
       break;
  }

   const Component = () => (
     <div>{strings[0] + colorStr}</div>
   );

   return Component;
}

Use the component like so.

const red = '#f00';
const ColorComponent = colorComp`Color is ${red}`;
<ColorComponent />

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.

Related Posts

Leave a Reply

Your email address will not be published.