Inserting html tags in template literals in React

You can use dangerouslySetInnerHTML to render HTML from a string with React, but make sure you only use it if you absolutely have to and you control the values.

Example

class App extends React.Component {
  state = {
    cityName: "New York",
    today: {
      weather_state_name: "Foo",
      min_temp: 0,
      max_temp: 10,
      humidity: 50
    }
  };

  render() {
    const { today } = this.state;
    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>
    `;
    return <div dangerouslySetInnerHTML={{ __html: weatherForecast }} />;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

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>
}

You need to parse HTML, because in your case it will show you your tags instead of making text strong.

You can use for example import ReactHtmlParser from 'react-html-parser';

ReactHtmlParser(weatherForecast)

Does it answer your question?


<div dangerouslySetInnerHTML={{__html: weatherForecast }} />

You can use this code to display.