Search code examples
reactjsconcatenation

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!


Solution

  • 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