Inserting html tags in template literals in React

Ivana picture Ivana · Mar 12, 2019 · Viewed 7.2k times · Source

I have variable with template literal in React:

const weatherForecast = `
  Today in <strong>${this.state.cityName}</strong>
  weather will be with <strong>${today.weather_state_name}</strong>,
  min temperature <strong>${parseInt(today.min_temp)}°C</strong>,
  max temperature <strong>${parseInt(today.max_temp)}°C</strong>,
  and humidity will be <strong>${today.humidity}%</strong>
`;

and I want to insert HTML code in it, as you can see that is tag . Is this possible and how can I do this. I googled it, but I couldn't find the answer.

Answer

Prithwee Das picture Prithwee Das · Mar 12, 2019
const weatherForecast = 
`Today in <strong>${this.state.cityName}</strong> weather will be with <strong>${today.weather_state_name}</strong>, min temperature <strong>${parseInt(today.min_temp)}°C</strong>, max temperature <strong>${parseInt(today.max_temp)}°C</strong>, and humidity will be <strong>${today.humidity}%</strong>`;

React will treat this as a string and not jsx. What you can do instead is

const weatherForecast = 
<p>Today in <strong>{this.state.cityName}</strong> weather will be with <strong>{today.weather_state_name}</strong>, min temperature <strong>{parseInt(today.min_temp)}°C</strong>, max temperature <strong>{parseInt(today.max_temp)}°C</strong>, and humidity will be <strong>{today.humidity}%</strong></p>;

and then render this in your render method like this

render(){
  return <div>{weatherForecast}</div>
}