Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template literals as string content in JSX

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!

like image 834
Tim Avatar asked Sep 04 '18 15:09

Tim


People also ask

What are template literals in JavaScript?

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.

What is a JSX tagged template literal?

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.

What are template literals in ES6?

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.

What is the difference between a tag and a template literal?

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.


1 Answers

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>
like image 167
WebDeg Brian Avatar answered Oct 07 '22 12:10

WebDeg Brian