bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/React/React Core Practice
React•React Core Practice

React ES6 Template Strings

Concept visual

React ES6 Template Strings

Graph traversalgraph
ABCDE
current
queued
1
4

Start from A

❮ Previous Next ❯

Template Strings

Template strings allow you to write strings that span multiple lines and include embedded expressions:

Example

Before:

const name = "John";
const age = 30;
const message = "Hello, " + name + "!\n" +
"You are " + age + " years old.";

Example

With Template Strings:

const name = "John";
const age = 30;
const message = `Hello, ${name}!
You are ${age} years old.`;
Template strings use backticks (`) instead of quotes and can include:

Multiple lines without \n

Expressions inside ${}

Quotes without escaping

Example

Multi-line Strings:

const html = `

<div>

Formula

< h1 > Title </h1 >
< p > Paragraph </p >

</div>

`;

Note:

Formula

The indentation in multi - line strings becomes part of the string.

Example

The indentation becomes part of the string:

const x = `

John:

Hello, how are you?

Jane:

I'm fine, thanks!

`;

Expression Interpolation

You can include any valid JavaScript expression inside

${}

in a template string:

Example

Insert variables inside template strings:

let firstName = "John";
let lastName = "Doe";
let text = `Welcome ${firstName}, ${lastName}!`;

Example

Insert expressions inside template strings:

let price = 10;
let quantity = 5;
let total = `Total: ${price * quantity}`;

Example

Using the map function inside template strings:

const items = ["apple", "banana", "orange"];
const list = `You have ${items.length} items:
${items.map(item => `- ${item}`).join('\n')}`;

Example

Using ternery operator inside template strings:

const isAdmin = true;
const message = `Status: ${isAdmin ? 'Admin' : 'User'}`;

Tagged Templates

You can also use template strings with a function (called a tag) to modify the output.

Note:

Tagged templates are an advanced feature. You might not need them in most cases. The function takes the text and the expression(s) as arguments.

Look at the example below:

Example

Previous

React ES6 Ternary Operator

Next

React Destructuring Props