All notes


Utilising tagged template literals (a recent addition to JavaScript) and the power of CSS, styled-components allows you to write actual CSS code to style your components.

Tagged Template Literals

Tagged Template Literals are a new feature in ES6. They let you define custom string interpolation rules.

//----- If you pass no interpolations, the first argument your function receives is an array with a string in it.

// These are equivalent:
fn`some string here`;
fn([ 'some string here' ]);

//----- Once you pass interpolations, the array contains the passed string, split at the positions of the interpolations. The rest of the arguments will be the interpolations, in order.

const aVar = 'good';

// These are equivalent:
fn`this is a ${aVar} day`;
fn([ 'this is a ', ' day' ], aVar);

An example in styled-components:

import React from 'react';

import styled from 'styled-components';

// Create a <Title> react component that renders an <h1> which is
// centered, palevioletred and sized at 1.5em
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;

// Create a <Wrapper> react component that renders a <section> with
// some padding and a papayawhip background
const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;

// Use them like any other React component – except they're styled!
  <Title>Hello World, this is my first styled component!</Title>