How to concatenate Strings and Variables in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
3 min

banner

# Concatenate strings and variables in React

Use a template literal to concatenate strings and variables in React, e.g. "<a href={https://example.com/${myPath}}".

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; const myPath = '/example/123'; const path = 'example'; const id = '123'; const url = `https://example.com/${path}/${id}`; console.log(url); // ๐Ÿ‘‰๏ธ "https://example.com/example/123" return ( <div> <a href={`https://example.com/${myPath}`} target="_blank" rel="noreferrer" > Example </a> <div className={`text-white ${myClass}`}>Apple</div> <br /> <div className={`some-class ${'hi'.length === 2 ? 'bg-yellow' : ''}`}> Banana </div> <h2 style={{ padding: `${num + num}px`, backgroundColor: 'lime', }} > Kiwi </h2> </div> ); }
The code for this article is available on GitHub

And here is the CSS for the examples.

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

react concatenate string and variable

The code for this article is available on GitHub

We used template literals to concatenate strings and variables in React.

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
<a href={`https://example.com/${myPath}`} target="_blank" rel="noreferrer" > Example </a> <div className={`text-white ${myClass}`}>Apple</div> <br /> <div className={`some-class ${'hi'.length === 2 ? 'bg-yellow' : ''}`}> Banana </div>

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

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

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

App.js
const path = 'example'; const id = '123'; const url = `https://example.com/${path}/${id}`; // ๐Ÿ‘‡๏ธ "https://example.com/example/123" console.log(url);

You can even call functions in template literals.

App.js
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}`} > bobbyhadz.com </div> </div> ); }
The code for this article is available on GitHub

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

# Conditionally concatenate a string and a variable

If you need to conditionally concatenate a string and a variable, use the ternary operator in your template literal.

App.js
const color1 = 'blue'; const color2 = 'red'; const result = `${color1.length > color2.length ? color1 : color2}`; console.log(result); // ๐Ÿ‘‰๏ธ blue

The ternary operator is very similar to an if/else statement.

If the expression to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise, the value to the right of the colon is returned.

You can imagine that the value before the colon is the if block and the value after the colon is the else block.

App.js
<div className={`some-class ${'hi'.length === 2 ? 'bg-yellow' : ''}`}> Banana </div>

The ternary operator in the example checks if the length of the string hi is equal to 2.

If the condition is met, the operator returns the string bg-yellow, otherwise, an empty string is returned.

Here is an example that concatenates a string and variable if a state variable is set to true.

App.js
import {useState} from 'react'; import './App.css'; export default function App() { const [isActive, setIsActive] = useState(false); const cls = 'bg-salmon'; return ( <div> <button className={isActive ? `text-white ${cls}` : 'bg-yellow'} onClick={() => setIsActive(isActive => !isActive)} > bobbyhadz.com </button> </div> ); }
The code for this article is available on GitHub

And here is the CSS for the example.

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

conditionally concatenate string and variable

We set the onClick prop on the button element, so every time the button is clicked a function is invoked.

Inside the function, we simply toggle the state of the isActive boolean.

We used the ternary operator to check if the state variable is equal to true.

App.js
<button className={isActive ? `text-white ${cls}` : 'bg-yellow'} onClick={() => setIsActive(isActive => !isActive)} > bobbyhadz.com </button>
The code for this article is available on GitHub

If the isActive state variable is equal to true, the string to the left of the colon gets returned, otherwise, the string to the right of the colon is returned.

The dollar sign and curly braces syntax will be evaluated if the condition is met and the string and variable will get concatenated to form the element's class name.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev