Languages
[Edit]
EN

React - variable in string

3 points
Created by:
starcraf35
754

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:

  1. Using template literals and ${expression}
  2. 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 );
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - variable in string
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join