Ad

React - How To Return HTML Elements In JSON

- 1 answer

I have a JSON file that contains HTML elements in a string - Is it possible to return the data in React/JSX as valid rendered HTML?

var Hello = React.createClass({
  render: function() {
    var exampleJSONData = {
        "item": "Hello",
        "text": "<p>Lorem ipsum</p><p>dolor sit amet</p>"
    }
    return <div>{data.item} {data.text}</div>;
  }
});

Returns : Hello <p>Lorem ipsum</p><p>dolor sit amet</p> instead of:

Hello
Lorem ipsum
dolor sit amet

fiddle

Ad

Answer

You can try use dangerouslySetInnerHTML like this

<div dangerouslySetInnerHTML={ {__html: data.text} } />

Example

Ad
source: stackoverflow.com
Ad