Guide to String Interpolation With React

Introduction

When working with strings, situations may arise that require us to dynamically add a specific value into such a string so that it still returns a string, the act of doing this is referred to as string interpolation.

This dynamic value could be a variable, state, or anything else that contains the actual value to be embedded in the string.

In this guide, we will look at how to implement string interpolation in React, taking into account the various instances that may require string interpolation and how they can be achieved.

String Interpolation in ES5 and ES6

String interpolation can be accomplished in two ways: concatenation and template literals. Although some argue that concatenation is not string interpolation, string interpolation refers to the ability to create strings by doing placeholder substitution, which concatenation clearly does.

Prior to the introduction of template literals in ES6, we had always used concatenation, which becomes very difficult when dealing with multi-line strings that require the substitution of many variables. When template literals were introduced in ES6, they proved far easier to implement, especially for longer or multi-line strings into which we want to embed expressions.

In this guide, we will look at both methods and then perform some examples with template literals, which is the recommended approach.

String Interpolation in React With Concatenation

The standard method for concatenation is by making use of the + operator around the particular variable or state:

const App = () => {
   const [fontSize] = useState('large');
   return (
      <div className="container">
         <h1 className={"font-bold text-" + fontSize}>Hello World</h1>
      </div>
   );
};

In the code above, we have the state of fontSize which has a value of large. We want the class to be fetched dynamically - for instance it could be text-small, text-large, text-medium, etc. Depending on the state, a different className will thus be applied to the heading!

With concatenation, we will first place our actual string and then make use of the+ operator to interpolate the variable with the actual string, so it could return the interpolated value:

The above method gets complex when there are two or more variables, and especially if the strings are added within another string, and not to the end.

String Interpolation to React with Template Literals

This is the best method for dealing with string interpolation. It was added in ES6 and has since become the most commonly used method for string interpolation. Using string template literals, let's repeat the preceding example:

const App = () => {
   const [fontSize] = useState('large');
   return (
      <div className="container">
         <h1 className={`font-bold text-${fontSize}`}>Hello World</h1>
      </div>
   );
};

As we can see in the code above, we no longer use the plus operator in template literals, instead, we use backticks for the entire string and then use the dollar sign and curly braces to insert our variables and dynamic values.

The statement is evaluated and const fontSize is inserted into the string.

Let's look at some more React string interpolation examples!

How to Make Use of String Interpolation to Pass Style Values in React

In a situation whereby we have our style data stored in a variable of which we want to use to style a text internally in React, we can make use of template literals:

const App = () => {
   const textSize = 40;
   return (
      <div className="container">
         <h1 style={{ fontSize: `${textSize}px` }}>Hello World</h1>
      </div>
   );
};

As we earlier said, the dollar sign and curly braces are used to hold our placeholder, and this will return the style in the proper way:

We could also perform evaluation within the curly braces, suppose we want the number to get multiplied:

<h1 style={{ fontSize: `${textSize * 2}px` }}>Hello World</h1>

How to Make Use of String Interpolation With Expressions in React

So far, we've seen that we can perform evaluations; it's also important to note that we can add expressions within the curly braces to get the correct value based on the expression and use it:

const App = () => {
   const [showNav, setShowNav] = useState(true);
   return (
      <div className="container">
         <div className={`navbar ${showNav ? 'mobile-nav' : ''}`}>NavBar</div>
      </div>
   );
};

How to Interpolate Multiple Line String With Template Literals

As we said earlier, the template literals make it easy to add placeholders to strings of multiple lines:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

const App = () => {
   let user = {
      name: 'John Doe',
      age: 14,
      hobby: 'basketball',
   };

   let sentence = `The fact that ${user.name} is ${user.age} years old and his hobby is ${user.hobby} amazes me.`;

   return (
      <div className="container">
         <div>
            <p>{sentence}</p>
         </div>
      </div>
   );
};

In the code above, we see how easy it is to use template literals compared to using concatenation:

let sentence = "The fact that " + user.name+ " is " +user.age+ " years old and his hobby is " +user.hobby+ " amazes me.";

How to Make Use of Logical Operators With Template Literals

So far we have seen how to pass expressions with ternary operators, it’s also best we see that logical operators can also work with template literals:

const App = () => {
   const [showNav, setShowNav] = useState(true);
   return (
      <div className="container">
         <div className={`navbar ${showNav && 'mobile-nav'}`}>NavBar</div>
      </div>
   );
};

Conclusion

We learned how to implement string interpolation using two standard methods in this article, as well as how powerful template literals can be. Since the introduction of template literals, most people prefer using them due to the simplicity of use and significantly better code readability.

Last Updated: June 2nd, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms