Search code examples
javascripthtmltagsjsxstring-interpolation

Put html tag within string interpolation


I want to put html-tags within a string interpolation

Ex:

A, B, C are object variables.

const string = `${A} (${B} / ${C})`; // This works

const string = `${A} (${<span className="text-light">{B} / {C})</span>}`; // What I want

When i render the string the span-tag shows up as text, it does not apply the html and css.

Can this be done somehow?


Solution

  • Not sure what you mean by object variables. But this should work just fine:

    let's say we have some variables defined:

    const A = `First value`;
    const B = `Second value`;
    const C = `Third value`;
    

    Your provided example is not properly formed:

    const string = `${A} (${<span className="text-light">{B} / {C})</span>}`;
    

    It should be like this:

    const string = `${A} <span className="text-light">(${B} / ${C})</span>`
    

    You always need to use dollar sign and opening curly brackets ${ before writing a variable name.

    Edit:

    If you have some HTML in your string it doesn't matter, everything is treated as characters in JavaScript, you won't get any formatting in the string or colors and such stuff, JavaScript has no way of knowing about that to have some visual changes you need to actually insert / append that string somewhere in the html document. It's just like a html template.