Borislav Hadzhiev
Fri Apr 29 2022·2 min read
Photo by Gracie Shafqat
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.
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.
.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.
The dollar sign and curly braces syntax allows us to use placeholders that get evaluated.
<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 second example in the code snippet uses the ternary operator.
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.
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.