String Interpolation in React (with examples)

avatar

Borislav Hadzhiev

Fri Apr 29 20223 min read

String Interpolation in React (with examples) #

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.

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

And here is the CSS for the example.

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

string interpolation

We can use a template literal to interpolate a variable in a string.

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}`}>Some content here</div> <div className={`text-white ${'hi'.length === 2 ? 'bg-salmon' : ''}`}> Some content here </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.

When you want to render a variable or expression in your JSX code, you have to wrap it in curly braces.

App.js
<h2>Hello {name}</h2>

You can also use template literals outside of your JSX code.

App.js
const num = 50; const result = `${num + 50} percent`; console.log(result); // 👉️ 100 percent

By default, the template literal concatenates the parts into a string.

You can also interpolate variables in multi-line strings using a template literal.

App.js
const color1 = 'red'; const color2 = 'blue'; const poem = `roses are ${color1} violets are ${color2}`; console.log(poem); // 👉️ roses are red // 👉️ violets are blue

This is very useful because we don't have to add a newline character on each line, as opposed to when concatenating strings.

You can even call functions in template literals.

App.js
import './App.css'; export default function App() { const subtract = (a, b) => { return a - b; }; const myClass = 'bg-salmon'; const num = 30; return ( <div> <div style={{fontSize: `${subtract(60, 20)}px`}} className={`padding-${subtract(100, 80)} text-white ${myClass}`} > Some content here </div> </div> ); }

Here's an example of using the ternary operator with template literals.

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' : ''}`}> Some content here </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.

You can also use the logical OR (||) and logical AND (&&) operators in a template literal.

App.js
const num1 = 0; const num2 = 100; const result = `${num1 || num2}`; console.log(result); // 👉️ 100

The logical OR (||) operator returns the value to the left if it's truthy, otherwise it returns the value to the right.

Here's an example of using the logical AND (&&) operator with template literals.

App.js
const bool = true; const str = 'hello'; const result = `${bool && str}`; console.log(result); // 👉️ hello

The logical AND (&&) operator returns the value to the left if it's falsy, otherwise it returns the value to the right.

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