WTF Strings
import gql from 'graphql-tag';
const query = gql`
{
user(id: 5) {
firstName
lastName
}
}
`
While perusing the lovely graphql-tag you may have wondered what the hell is going on with that string. You’re not the only one. At a recent React JAX meetup, someone asked about it and no one could really explain it other than, “ES6 stuff.”
It is a tagged template literal.
This is a way to call a function and pass it a string with the components needed
to interpolate it… yourself… with no ()
… and no need for a return…
plus fun side effects… and weird hidden props.
Aside - I think Douglas Crockford may have dug his own grave just so he could spin in it after seeing this bullshit.
Simple Example
function doStringStuff(strings, ...values) {
console.log(strings)
console.log(values)
}
const adjective = 'wonderful'
const user = 'Farm Boy'
doStringStuff`
Hey, man!
I'm doing some cool string manipulation.
It is ${adjective}.
Love,
${user}
`
Here’s what the above will give you.
// The plain Jane strings in an array.
[
'\n Hey, man!\n I\'m doing some cool string manipulation.\n It is ',
'.\n Love,\n ',
'\n',
]
// The values to be plugged in.
[
'wonderful',
'Farm Boy',
]
That’s all you need to know, really. If you want more, there is a beautiful explanation here. It may also be helpful to open the Babel REPL and play around.