lost9123193 lost9123193 - 26 days ago 4x
React JSX Question

Concatenating variables and strings in React

Is there a way to incorporate React's curly brace notation and an

tag? Say we have the following value in the state:


and the following HTML attributes on a tag:


Is there a way I can add the
state to the HTML attribute to get something like this:

href={"#demo + {this.state.id}"}

Which will yield:



You're almost correct, just misplaced a few quotes. You can do:

href={'#demo' + this.state.id}

This will use the string #demo and concatenate it to this.state.id. This can then be applied to all strings. Consider this:

var text = "world";

And this:

{"Hello, " + text + " Andrew"}

This will yield:

Hello world Andrew 

You can also use ES6 string interpolation with ` and ${var}:


This will basically substitute the value of this.state.id into #demo and is equivalent to doing: "#demo" + this.state.id.