Languages
[Edit]
EN

React - variable in string

3 points
Created by:
Dirask Community
5850

In this article we would like to show you how to put a variable inside a string in React.

Quick solution:

// 1
var text = 'world';
<h1>{`Hello ${text}`}</h1>

// 2
var text = 'world';
<h1>{"Hello " + text}</h1>

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';

var 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';

var text = 'world';

const App = () => {
  return (
    <div>
      {'Hello ' + text}
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

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