HTTP
HTTP

Reputation: 1724

How to concat a string and a props in React

This is just a question to clarify what I know and understand about React concatenating string and props. I have a simple code like

const foo = bar?'test--${bar}':''

When I am logging out foo, it shows test--${bar} instead of test--whatever. If I try to do

const foo = bar?'test--' + bar:''

It will give me the answer I am expecting to be. Can someone explain to me why. I was just started learning React. I scanned through some questions here and they said the best way to concat string and props is to do the first one but why its not working on me. Am I missing something? Thanks!

Upvotes: 1

Views: 3884

Answers (2)

Sahil.
Sahil.

Reputation: 1

Use backticks (`) instead of single quotes and it will work.

//Correct
const foo = bar?`test--${bar}`:'whatever';

//Incorrect
const foo = bar?'test--${bar}':'whatever'

Upvotes: 0

Ajay Gupta
Ajay Gupta

Reputation: 2033

It is because you are not using template literals.

Try it like this:

const bar = "typo";
const foo = bar ? `test--${bar}` : "nope";

console.log(foo);

Reference article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Upvotes: 2

Related Questions