How can I interpolate JSX with an expression in a string?

Reactjs

Reactjs Problem Overview


Looking to achieve the following:

<div className="total total-{obj.state}">

Obviously this compiles to:

<div class="total total-{obj.state}">

Is there an elegant way in JSX to evaluate the expression in the {} within a string?

Reactjs Solutions


Solution 1 - Reactjs

Try this (ES5):

<div className={'total total-' + obj.state}>...</div>

Or with ES6+

<div className={`total total-${obj.state}`}>...</div>

Remember that everything between { and } is just Javascript, so the expression is 'total total-' + obj.state which is then set as the class of the DOM node.

Solution 2 - Reactjs

You could use a react expression and then the javascript es6 string interpolation

Something like this:

<div someProp={`${SomeConstOrVariableOrExpression} simple text`}></div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionbenhowdle89View Question on Stackoverflow
Solution 1 - ReactjsAnders EkdahlView Answer on Stackoverflow
Solution 2 - ReactjspedrommullerView Answer on Stackoverflow