javascriptecmascript-6graphqlstyled-componentstemplate-literals

What is the purpose of template literals (backticks) following a function in ES6?


In GraphQL you can write something like this to define a query:

const USER_QUERY = gql`
  {
    user(id: 2) {
      name
    }
  }
`

In styled components you can define a styled component like this:

const Button = styled.button`
    background-color: papayawhip;
`

What is this syntax? I know with template literals you can sub in variables with this syntax: ${foo} but I have never seen this used. Any guidance would be appreciated.


Solution

  • These are tagged template literals. The part before the backticks is a reference to a function that will be called to process the string.

    The function is passed the variables (the ${} parts) as arguments as well as the pieces of the string that surround the variables broken into an array. The return value of the function becomes the value of the template. Because of this very generalized format, you can do almost anything with the function. Here's a quick and dirty example that takes the variables (gathered into an array for convenience,) makes them uppercase, and puts them back in the string:

    function upperV(strings, ...vars) {
      /* make vars uppercase */
      console.log("vars: ", vars)       // an array of the passed in variables
      console.log("strings:", strings)  // the string parts
    
      // put them together
      return vars.reduce((str, v, i) => str + v.toUpperCase() + strings[i+1], strings[0]);
    }
    
    let adverb = "boldly"
    let output = upperV`to ${adverb} split infinitives that no ${'man'} had split before...`;
    console.log(output)