So currently I'm going for the effect of trying to display formatted code or in this case a graphql operation in my react app. Triggered by state, I want to display or remove certain variables.
const testing = `query {
getBooks {
${value.bookId?"id" : ""}
${value.bookEntry?"entry" : ""}
${value.bookTitle?"title" : ""}
}
}`
...
<div className="output">
<pre>
<code>{testing}</code>
</pre>
</div>
I'm stuck rendering something that looks like this!
There's probably a better way to go around this, but it's worth asking!
Add a filter to remove whitespaces before rendering.
Check my solution below:
// Solution:
function clearQueryString(queryString){
const result = []
const splitted = queryString.split('\n')
console.log({splitted})
for (let index = 0; index < splitted.length; index++) {
const element = splitted[index];
// regex credit: https://stackoverflow.com/questions/10261986/how-to-detect-string-which-contains-only-spaces/50971250
if (!element.replace(/\s/g, '').length) {
console.log(`#${index} string only contains whitespace!`);
} else {
result.push(element)
}
}
return result.join('\n')
}
// Usage:
const value = {}
const testing = `query {
getBooks {
${value.bookId?"id" : ""}
${value.bookEntry?"entry" : ""}
${value.bookTitle?"title" : ""}
author
otherfield
}
}`
document.getElementById('codeOutput').innerHTML = clearQueryString(testing);
<div className="output">
<pre>
<code id="codeOutput"></code>
</pre>
</div>