Search code examples
htmlcssreactjsrender

Unable to render html tags that were returned by the server dynamically


In my React project, I make an API call to the server which returns some HTML that I have to render. Below is the API call result:
enter image description here

So this unit_configuration_label field does not properly render. The styling that I applied to that b-tag does not apply. I guess its because the page renders first before I get the results from the server, and then when we get it, it just appends this result as a string, this is what I get on render:
enter image description here

And I need to append that HTML inside this span-tag

      <div className="room-types">
        <span>{hotel.unit_configuration_label}</span>
      </div>

Solution

  • use "dangerouslySetInnerHTML":

      const data = "Twin Room with Bath </br><b>Hotel room</b>:2 beds";
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
          <div
          dangerouslySetInnerHTML={{__html: data}}
        />
        </div>
      );
    

    https://codesandbox.io/s/stoic-hypatia-ljyb02