How To Concatenate Variables and Strings in JSX and React.js

When specifying properties of React components, there are many situations where a combination of a string and variable is required. Simply appending a variable to a string seems unintuitive.

So, how can you concatenate variables and strings in JSX?

Let’s say we have a button component: and this Button component has mode prop that accepts three modes:

  • mode1
  • mode2
  • mode3

The source of truth for the mode prop comes from our component’s state:

this.state = {
 modeNumber: '1'
}

So here is our Button component trying to add the string literal mode with this.state.modeNumber:

<Button name="test-button" mode="mode + {this.state.modeNumber}" />

The modeproperty won’t work here as the value of the property is interpreted as a string.

Instead, we want to dynamically use this value for the Buttoncomponent’s mode property. This is made relatively simple – specify the following in the render function:

render() {
 const { modeNumber } = this.state;
 return <Button name="#demo1" mode={"mode" + modeNumber} />
}

Anything inside {} is an inline JSX expression, so modeNumber is evaluated correctly here. Additionally, we can also do this a more concise way using ES6’s template literals

render() {
const { modeNumber } = this.state;
return <Button name="#demo1" mode={`mode${modeNumber}`} />
}

And there you have it, when trying to combine state with a string you need to indicate which part of the text is a variable and which is a string literal.

 

Gareth Dunne

Senior JavaScript Engineer and creator of JSdiaries. Passionate about the latest in web technologies and how it can provide value for my clients.