Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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?

like image 376
benhowdle89 Avatar asked May 21 '15 11:05

benhowdle89


People also ask

How do you use string interpolation in React?

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.

Can I put JSX expression to the variable?

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.

How do you interpolate a string in JavaScript?

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.

How do I convert a string to JSX?

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.


2 Answers

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.

like image 122
Anders Ekdahl Avatar answered Sep 20 '22 17:09

Anders Ekdahl


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

Something like this:

<div someProp={`${SomeConstOrVariableOrExpression} simple text`}></div> 
like image 28
pedrommuller Avatar answered Sep 24 '22 17:09

pedrommuller