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:
// 1
const text = 'world';
<h1>{`Hello ${text}`}</h1>
// 2
const text = 'world';
<h1>{'Hello ' + text}</h1>
// 3
const text = 'word';
const result = `Hello ${text}`;
// 4
const text = 'word';
const result = 'Hello ' + text;
The below examples present two ways to do that:
- Using template literals and
${expression}
- By concatenating variable and string.
1. Using template literals and ${expression}
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:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const text = 'world';
const App = () => {
return (
<div>
{`Hello ${text}`}
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
2. Concatenating variable and string
In below example we create text
variable and concatenate it to 'Hello '
string inside curly braces, then we display exerything in <div>
.
Runnable example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const text = 'world';
const App = () => {
return (
<div>
{'Hello ' + text}
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );