How to insert HTML inside template literal strings?

Viewed 3141

In React, I want to be able to use style words within a string which is defined in a variable using template literals. For that I am making use of a to just style that word. I am getting HTMLIntrinsic usage error.

Note- Solutions given in SO to questions related to this does not solve the issue I have. Pls check the code.

How to circumvent this problem

Tried using dangerouslyinsertHTML, but not a recommended solution.

    //Actual code
    const temperature = "22";
    const list = {
       item: `The temperature is ${temperature}`
    }

    //To style it-
    const temperature = "22";
    const list = {
       item: `The temperature is <span style={{color:'red'}}>${temperature}</span>`
    }

    //And the above list.item is inserted inside JSX like -
    return (
      <div>{list.item}</div>
    )

The temperature(22) needs to be styled.

3 Answers

Instead of the template string, you can use JSX elements for generating HTML as usual, placed next to your text elements. Example:

item: (
  <>
    The temperature is
    <span style={{color:'red'}}>
      {temperature}
    </span>
  </>
)

I'm using a Fragment to wrap the text and elements together, but you can use something else like a div if you wish to style the wrapper too.

You can't use React in template-literal like that because the React component is an object. Using it with template-literal will result in this[object Object] . So I recommend use other way, for example the solution by @richardo

You can make this as simple as this, IF you are OK to not have object like you defined

return(
  <div>The temperature is <span style={{color: 'red'}}>{temperature}</span></div>
)
Related