Concatenating variables and strings in React

Concatenating Variables and Strings in React

When working with React, you may find yourself needing to concatenate variables and strings. There are a few ways to accomplish this.

Using Template Literals

One way to concatenate variables and strings in React is to use template literals. Template literals allow you to embed expressions inside of a string literal. To use template literals in your React code, wrap your string in backticks (`) and use the ${} syntax to insert variables or expressions.


const name = 'Raju';
const greeting = `Hello, ${name}!`;

return (
  <div>
    <p>{greeting}</p>
  </div>
);
  

Using the + Operator

Another way to concatenate variables and strings in React is to use the + operator. Simply add the variables or expressions together within the curly braces.


const firstName = 'Raju';
const lastName = 'Singh';

return (
  <div>
    <p>My name is {firstName + ' ' + lastName}.</p>
  </div>
);
  

Using Array Join

You can also use the array join method to concatenate variables and strings. First, create an array containing the variables or expressions you want to concatenate. Then use the join method to combine them into a single string.


const hobbies = ['coding', 'reading', 'traveling'];

return (
  <div>
    <p>My hobbies are: {hobbies.join(', ')}</p>
  </div>
);
  

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe