Tagged Template Literals

A tagged template literal gives us back as the first argument everything besides the interpolated portion and the interpolated value as the second argument:

interpolation

Tagged template literals can also return a function which can then be executed:

const logFunction = () => {
  return 'Returned from logFunction!';
};

const myTag = (literals, func) => {
  // literals is ["Function expression in template", ""]
  // so we only want the first element
  return literals[0] + func();
};

const taggedResult = myTag `Function expression in template: ${() => logFunction()}`;
console.log(taggedResult); 
> "Function expression in template: Returned from logFunction!"

This is the entire premise of which styled components is built upon. Read more about that and the breakdown in this article.

Read more about template literals here

Instagram Post