Tagged Template Literals
Hello Everyone 👋,
Tagged template literals is an es6 feature which allow you to tag a template to a function.
If you are from react/graphql world you would have seen the below syntax.
Even If you do not know this syntax follow along you will understand.
Here styled.button and gql are actually just functions.
See the below example
Whenever a tagged function is called the first argument will be array of strings which is split on the interpolation.
Notice that we have used second argument with rest operator because each interpolation value will be passed as an argument to the function. Imagine there are 10 interpolation in a string getting each argument separately is not a good practice.
This can be used to completely transform the string.
Consider a use case while rendering a block in the html all its dynamic values needs to be made bold. We can write a simple function with tagged template easily to preprocess the string for us.
Note: There will be always one value more in the strings array then the values
Check out these awesome libraries that use tagged templates:
Please like and share if you find this interesting.