277

Is there a way to incorporate React's curly brace notation and an 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:

#demo1
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
lost9123193
  • 10,460
  • 26
  • 73
  • 113

5 Answers5

529

You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string #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.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • Implementing the first, eslint suggested implementing your second, use string literal templates. https://eslint.org/docs/rules/prefer-template – w00ngy Sep 10 '19 at 13:22
  • @w00ngy Yes, you should. ES2015 (which introduced templates) was just starting to get widespread adoption. Nowadays, template literals are the go to. – Andrew Li Sep 10 '19 at 14:42
74

the best way to concat props/variables:

var sample = "test";    
var result = `this is just a ${sample}`;    
//this is just a test
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Kevin Laurente
  • 740
  • 6
  • 6
24

If u want to do it in JSX

<button className={`tab__btn first ${props.state}`} >
    {props.text}
</button>
Hyzyr
  • 568
  • 4
  • 13
8

you can simply do this..

 <img src={"http://img.example.com/test/" + this.props.url +"/1.jpg"}/>
Michael
  • 131
  • 1
  • 2
1

for Concatenating variables and strings in React with map , for exmple :

{listOfCategories.map((Categories, key) => { return ( <a href={`#${Categories.designation}`} className="cat-link" key={key}> </div> </a> ); })}
yassine dotma
  • 697
  • 8
  • 10