EN
React - variable in string
3 points
In this article, we would like to show you how to put a variable inside a string in React.
Quick solution:
xxxxxxxxxx
1
// 1
2
const text = 'world';
3
<h1>{`Hello ${text}`}</h1>
4
5
// 2
6
const text = 'world';
7
<h1>{'Hello ' + text}</h1>
8
9
// 3
10
const text = 'word';
11
const result = `Hello ${text}`;
12
13
// 4
14
const text = 'word';
15
const result = 'Hello ' + text;
The below examples present two ways to do that:
- Using template literals and
${expression}
- By concatenating variable and string.
Template literals allow us embed expression, so creating text
string using ``
(backticks) we can add our variable with ${text}
expression to the string.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const text = 'world';
6
7
const App = () => {
8
return (
9
<div>
10
{`Hello ${text}`}
11
</div>
12
);
13
};
14
15
const root = document.querySelector('#root');
16
ReactDOM.render(<App />, root );
In below example we create text
variable and concatenate it to 'Hello '
string inside curly braces, then we display exerything in <div>
.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const text = 'world';
6
7
const App = () => {
8
return (
9
<div>
10
{'Hello ' + text}
11
</div>
12
);
13
};
14
15
const root = document.querySelector('#root');
16
ReactDOM.render(<App />, root );