I'm wondering whats the best practice for strings values mixed with variables inside JSX tags, I've listed the options I'm familiar with:
render() {
const {totalCount} = this.state;
const totalCountStr = `Total count: ${totalCount}`;
return (
<div>
<h1>Total count: {totalCount}</h1> // 1
<h1>`Total count: ${totalCount}`</h1> // 2
<h1>{totalCountStr}</h1> // 3
</div>
);
}
What's the best practice or the use cases to use them differently?
Thanks!
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification.
If any component in the JSX is async (returns a Promise ), the tagged template literal itself returns a Promise for the final, complete result. This lets you create async component functions and await the final template result.
Template Literals is an ES6 feature (JavaScript 2015). Template Literals is not supported in Internet Explorer. Complete JavaScript String Reference. The reference contains descriptions and examples of all string properties and methods.
Also, a tagged template literal may not result in a string; it's up to the tag function what it creates (if anything). Template literals are enclosed by the backtick (` `) ( grave accent) character instead of double or single quotes. Template literals can contain placeholders.
Template literals aren't supported by React JSX currently. The correct way to do it is like so:
<h1>Total count: {this.state.totalCount}</h1>
Edit: Your third way is also correct, but I personally wouldn't recommend it because of debug issues as you would need to scan for brackets as the code expands
<h1>{`Total count: ${this.state.totalCount}`}</h1>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With