Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating variables and strings in React

People also ask

How do you concatenate a variable to a string in React?

Use a template literal to concatenate strings and variables in React, e.g. "<a href={ https://example.com/${myPath} }". Template literals are delimited with backticks and allow us to embed variables and expressions using the dollar sign and curly braces ${expression} syntax.

How do you combine variables and strings?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect. let myPet = 'seahorse'; console.

How do I combine numbers and strings?

To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.

Can you use += for string concatenation?

The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b .


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.


the best way to concat props/variables:

var sample = "test";    
var result = `this is just a ${sample}`;    
//this is just a test

you can simply do this..

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

If u want to do it in JSX

<button className={`tab__btn first ${props.state}`} >
    {props.text}
</button>

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> ); })}