String concatenation in React props

avatar

Borislav Hadzhiev

Fri Apr 29 20222 min read

String concatenation in React props #

Use a template literal to concatenate a string in React props, e.g. <div className={border ${myClass}}>. Template literals are delimited with backticks and allow us to embed variables and expressions using the dollar sign and curly braces ${expression} syntax.

App.js
import './App.css'; export default function App() { const myClass = 'bg-salmon'; const num = 30; return ( <div> <div className={`text-white ${myClass}`}>Hello world</div> <br /> <div className={`text-white ${'hi'.length === 2 ? 'bg-salmon' : ''}`}> Hello world </div> <h2 style={{ padding: `${num + num}px`, backgroundColor: 'lime', }} > Hello world </h2> </div> ); }

And here is the CSS for the example.

App.css
.bg-salmon { background-color: salmon; } .text-white { color: white; }

We can use a template literal to concatenate a string and a variable in React props.

Note that the string is enclosed in backticks ``, not in single quotes.

The dollar sign and curly braces syntax allows us to use placeholders that get evaluated.

App.js
<div className={`text-white ${myClass}`}> Hello world </div> <div className={`text-white ${'hi'.length === 2 ? 'bg-salmon' : ''}`}> Hello world </div>

The curly braces we wrapped the template literal in mark the beginning of an expression that has to be evaluated.

The code between the opening an closing curly brace is just JavaScript, so any variable or expression we use in our template literals will get evaluated.

The second example in the code snippet uses the ternary operator.

App.js
const color1 = 'blue'; const color2 = 'red'; const result = `${color1.length > color2.length ? color1 : color2}`; console.log(result); // 👉️ blue

The ternary operator is basically an if/else statement. The part before the question mark gets evaluated and if it returns a truthy value, the operator returns the value before the colon, otherwise it returns the value after the colon.

App.js
import './App.css'; export default function App() { return ( <div> <div className={`text-white ${'hi'.length === 2 ? 'bg-salmon' : ''}`}> Hello world </div> </div> ); }

The ternary operator in the example checks if the length of the string hi is equal to 2 and if it is, it returns the string bg-salmon, otherwise an empty string is returned.

Use the search field on my Home Page to filter through my more than 1,000 articles.