Concatenating Variables and Strings in React

Concatenating variables and strings in React

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.

How to concatenate a variable and string inside a prop in Javascript?

Assuming you're using react, you can use a template literal:

<TextField
label="First Name"
defaultValue={`My name is ${name}`}
/>

String and state variable concatenation

If you don't want to use ES6 templating, do it the old way but remove the extra brackets ({}) around the variables.

var url = "http://localhost:3000/get-players/" + this.state.city + "/" + this.state.sport;

How to concatenate {variable} to href tag in react js?

Try with template literals

href={`mailto: ${entry.email}`}

or

href={"mailto: "+ entry.email}

How to concatenate two JSX fragment or variables or string and component (in Reactjs)?

Use arrays:

let lineComponent = <Line key={line.client_id} line={line}/>;
if (line.created_at) {
return [
<div key="date" className="date-line"><strong>{line.created_at}</strong></div>,
lineComponent,
];
} else {
return chat_line;
}

Or use fragments:

import createFragment from "react-addons-create-fragment";

let lineComponent = <Line key={line.client_id} line={line}/>;
if (line.created_at) {
return createFragment({
date: <div className="date-line"><strong>{line.created_at}</strong></div>,
lineComponent: lineComponent,
});
} else {
return chat_line;
}

In both cases, you have to provide keys for React. In case of array, you set key directly on element. Regarding fragments, you provide key:element pairs.

NOTE:
When returning from render method, you can only return single element, or NULL. Examples provided are invalid in that case.



Related Topics



Leave a reply



Submit