Template strings (often called Template Literals) are an ES6 feature that allows you to easily embed variables and expressions directly into strings.
Before ES6, combining text and variables required tedious string concatenation using the plus + operator. Template strings simplify this greatly and are extremely useful in React, particularly when dealing with dynamic styling, class names, or string props.
Template strings are enclosed by backticks (` `) instead of single or double quotes.
Inside the backticks, you can inject JavaScript variables and expressions using the dollar sign and curly braces ${} syntax (called string interpolation).
const name = "John"; const age = 30;const text = "My name is " + name + " and I am " + age + " years old.";
const name = "John"; const age = 30;const text =
My name is ${name} and I am ${age} years old.;
The code is much cleaner, easier to read, and less prone to missing space errors.
Another great feature of template literals is that they support multi-line strings automatically. If you press 'Enter' inside backticks, the new line is preserved.
const multilineText = ` This string spans multiple lines without needing escape characters! `;
In React, template literals really shine when you need to dynamically construct strings based on props or state.
One of the most common use cases is conditionally adding CSS classes to elements based on state.
Let's say we have a button that needs the class btn, but if it's currently active, it also needs the class btn-primary.
import React, { useState } from 'react';const ToggleButton = () => { const [isActive, setIsActive] = useState(false);
// Using template strings with a ternary operator! const btnClass =
btn ${<span style="color: #008c8f;">isActive</span> ? 'btn-primary' : 'btn-secondary'};return ( <button className={btnClass} onClick={() => setIsActive(!isActive)} > {isActive ? "On" : "Off"} </button> ); };
You can also use template strings directly inside JSX when passing props or generating URL links.
const UserProfile = ({ username, userId }) => { return ( <div> <h1>{`Welcome, User ${username}!`}</h1> <img src={`https://avatars.example.com/${userId}.jpg`} alt="Avatar" /> </div> ); };
Notice how the src attribute of the image perfectly handles building a dynamic URL by embedding the userId variable using template strings.
${variable}.Which syntax is used to inject a variable named 'score' into a template string?