Skip to content

Instantly share code, notes, and snippets.

@joeytwiddle
Last active March 21, 2018 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeytwiddle/5705025a52abeb7ca78e6477ad90bf1d to your computer and use it in GitHub Desktop.
Save joeytwiddle/5705025a52abeb7ca78e6477ad90bf1d to your computer and use it in GitHub Desktop.
What do ES6 tagged templates do?
/*
* A tagged template happens when we call a function with a template string, but without parentheses.
*
* exampleFunc`template ${foo} string`
*
* What this does is to break the template down into the pure string parts, and the expressions.
*
* The function will be given an array as its first argument, containing all the strings.
* And the remaining arguments will be the evaluated expressions.
*
* This will allow the func to rebuild (interpolate) the template string, if it wants to,
* possibly changing the behaviour.
* Or it can just take the broken down (parsed) template, and use it in other ways.
*/
// Using an ES6 template string for styled components
const SuperCustomButton1 = styled.button`
background: ${props => props.theme.primary};
${baseButton}
border-radius: 20px;
padding: ${props => 50 * Math.random()}px;
`
// But what will that actually do?
// Let's see the equivalent code in ES5 (with ES6 arrow functions)
const SuperCustomButton2 = styled.button([
'\n background: ',
';\n ',
'\n border-radius: 20px;\n padding:',
'px;'
], props => props.theme.primary, baseButton, props => 50 * Math.random())
// The equivalent code in pure ES5
const SuperCustomButton2 = styled.button(
// First argument: An array containing the strings from the template
[
'\n background: ',
';\n ',
'\n border-radius: 20px;\n padding:',
'px;'
],
// Remaining arguments: Each of the expressions (one fewer than the strings)
function (props) {
return props.theme.primary
},
baseButton,
function (props) {
return 50 * Math.random()
}
)
/*
* In the example above, we sometimes pass functions instead of evaluated expressions.
* This allows the styled-components library to evaluate the functions later, at runtime,
* which could happen multiple times.
*
* You can read more about tagged templates on MDN: https://mdn.io/tagged+templates
*/