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?
Use a template literal for string interpolation in React, e.g. <div className={ text-white ${myClass} }> . Template literals are delimited with backticks and allow us to embed variables and expressions using the dollar sign and curly braces ${expression} syntax.
Using JSX, you can create a function and return a set of JSX elements to a variable, and that variable used is to render the elements inside the render() function in React.
You can add values into a JavaScript string using a template literal. This is a dollar sign followed by a pair of curly brackets. Within the curly brackets should be the expression whose value you want to embed in the string.
There're several ways to convert HTML Strings to JSX with React. One way is to put the string in between curly braces in our component. Another way is to put the string in an array with other strings or JSX code. Finally, we can use the dangerouslySetInnerHTML prop render an HTML string as HTML in our component.
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.
You could use a react expression and then the javascript es6 string interpolation
Something like this:
<div someProp={`${SomeConstOrVariableOrExpression} simple text`}></div>
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