Last updated: Apr 7, 2024
Reading timeยท3 min
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.
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> ); }
And here is the CSS for the examples.
.bg-salmon { background-color: salmon; } .bg-yellow { background-color: yellow; } .text-white { color: white; }
We used template literals to concatenate strings and variables in React.
The dollar sign and curly braces syntax allows us to use placeholders that get evaluated.
<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.
You can also use template literals outside of your JSX code.
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.
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> ); }
By default, a template literal concatenates the parts into a string.
If you need to conditionally concatenate a string and a variable, use the ternary operator in your template literal.
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.
<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
.
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> ); }
And here is the CSS for the example.
.bg-salmon { background-color: salmon; } .bg-yellow { background-color: yellow; } .text-white { color: white; }
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
.
<button className={isActive ? `text-white ${cls}` : 'bg-yellow'} onClick={() => setIsActive(isActive => !isActive)} > bobbyhadz.com </button>
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.