ReactJS Append variables with strings, jsx state and prop concatenate html

This tutorial shows multiple examples of concatenating strings with variables in the ReactJs Component.

React append string data variable

This example shows a string variable concatenation in React Component.

Created two string variables that hold string content. Append one string to another using the +operator. In the component, String is displayed using javascript expression. Let’s create a simple function component.

import React from "react";

const MyFunction = () => {
  let hello = "Hello ";
  let result = hello + " Welcome";

  return (
    <div>
      <div> {result} My application</div>
    </div>
  );
};
export default MyFunction;

Output:

Hello, John Welcome to My application.

React append HTML raw string into the string data variable

This example shows a concatenate HTML string content into another string constant.

Declared HTML raw string enclosed in double-quotes and append to string variable constant.

In the component, String is displayed using javascript expression.

import React from "react";

const MyFunction = () => {
  let hello = "Hello <div style='color: red'>";
  let result = hello + " John</div>";

  return (
    <div>
      <div> {result} Welcome to My application</div>
    </div>
  );
};
export default MyFunction;

Output:

Hello
<div style="color: red">John</div>
Welcome to My application

How to append string variable to href image tag in JSX

This example shows an anchor link and the href is dynamically appended with a string variable.

Anchor link used with href generated dynamically in two ways One way, using javascript expression {}, contains strings appended with constant and variable.

        <a href={"mailto:" + adminEmail}>Contact Admin </a>

Another way, use ES6 template literal syntax variable is included with interpolation syntax($),wrapped inside a backtick symbol.

<a href="{`mailto:${supportEmail}`}"> Contact Support </a>

It replaces the variable value at runtime.

Please note that wrapped inside the backtick not a single quote.

Here is a complete example

import React from "react";

const MyFunction = () => {
  let adminEmail = "[email protected]";
  let supportEmail = "[email protected]";

  return (
    <div>
      <a href={"mailto:" + adminEmail}>Contact Admin </a>
      <a href={`mailto:${supportEmail}`}> Contact Support </a>
    </div>
  );
};
export default MyFunction;

You can also append react state or props strings into URLs for anchor tags using append or es6 template literal syntax.

Conclusion

In React application, You can append string variables with constants or state or props strings with the below two approaches.

  • Append string with + symbol
  • ES6 template literal Syntax