7

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!

Tim
  • 165
  • 3
  • 9
  • I don't think #2 works. You could inline #3, but it would be very unappealing, especially compared to #1. – Bergi Sep 04 '18 at 15:09

1 Answers1

9

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>
WebDeg Brian
  • 802
  • 1
  • 7
  • 21