patternjavascriptreactCritical
Concatenating variables and strings in React
Viewed 0 times
stringsandreactvariablesconcatenating
Problem
Is there a way to incorporate React's curly brace notation and an
and the following HTML attributes on a tag:
Is there a way I can add the
Which will yield:
href tag? Say we have the following value in the state:{this.state.id}and the following HTML attributes on a tag:
href="#demo1"
id="demo1"Is there a way I can add the
id state to the HTML attribute to get something like this:href={"#demo + {this.state.id}"}Which will yield:
#demo1Solution
You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string
This will use the string literal
And this:
This will yield:
You can also use ES6 string interpolation/template literals with
#demo + {this.state.id} - you need to indicate which are variables and which are string literals. Since anything inside {} is an inline JSX expression, you can do:href={"#demo" + this.state.id}This will use the string literal
#demo and concatenate it to the value of 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/template literals with
(backticks) and ${expr} (interpolated expression), which is closer to what you seem to be trying to do:
href={`#demo${this.state.id}`}
This will basically substitute the value of this.state.id, concatenating it to #demo. It is equivalent to doing: "#demo" + this.state.id`.Code Snippets
href={"#demo" + this.state.id}var text = "world";{"Hello " + text + " Andrew"}href={`#demo${this.state.id}`}Context
Stack Overflow Q#39523040, score: 562
Revisions (0)
No revisions yet.