Tagged Templates


While using styled-components, I was amazed by this amazing syntax that allows us to set component styles dynamically.

I was wondering what that was and started looking for the answer. Thanks to the great documentation of style-components, it didn’t take too much time for me to figure out.

const Button = styled.button<{ $primary?: boolean; }>`
  /* Adapt the colors based on primary prop */
  background: ${props => props.$primary ? "#BF4F74" : "white"};
  color: ${props => props.$primary ? "white" : "#BF4F74"};

  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid #BF4F74;
  border-radius: 3px;

    <Button $primary>Primary</Button>

Before moving on to advanced use of string interpolation, let’s start with template literals first.

Template literals are easy way to combine expressions with strings. This process is called String Interpolation.

const username = "justaplant";
const prompt = `Hello, ${username}!`;

In this example, placeholder ${username} will be replaced with username. Can you guess what the evaluated string will be?

🥁🥁🥁 drum rolls 🥁🥁🥁

You’re right! The answer is Hello, justaplant!

Tagged Templates are basically advanced version of Template Literals that you can parse with functions.