5

I get a list of objects from the API. One of the values of each object is a plain string:

snippet: "Chainsmokers were re-formed as an EDM DJ duo in 2012 under the management of <span class="searchmatch">Adam</span> Alpert in New York City. Pall, who had grown up DJing, was introduced to"

I'd like to convert this plain string to be interpreted as html. How do I do that?

Edit: What I try to do is map over a list in React like so:

const list = props.responseData.map(item => (
<li key={item.pageid}>
  {item.title}
  <br />
  {item.snippet}
</li>
));

The snippet one is displayed as a plain string, not as HTML code. Writing item.snippet.innerHTML doesn't work. It displays an empty list.

  • What technology are you using in frontend? – Hassan Imam Oct 15 '17 at 15:53
  • 1
    @Hassan Imam's question is a good one. What you have is already valid HTML. –  Oct 15 '17 at 15:54
  • React. It just displays the response with tags as plain text. I want to be able to display etc as html code –  Oct 15 '17 at 15:56
  • 1
    Possible duplicate of [Render HTML string as real HTML in a React component](https://stackoverflow.com/questions/39758136/render-html-string-as-real-html-in-a-react-component) – Hassan Imam Oct 15 '17 at 16:15

2 Answers2

11

I figured it out. I need to put it inside a div with a special attribute:

<div dangerouslySetInnerHTML={{ __html: item.snippet }} />

LIVE EXAMPLE

class App extends React.Component {

constructor() {
    super();
    this.state = {
      snippet: `Chainsmokers were re-formed as an EDM DJ duo in 2012 under the management of <span class="searchmatch">Adam</span> Alpert in New York City. Pall, who had grown up DJing, was introduced to`
    }
  }

  render() {
    return (
      <div dangerouslySetInnerHTML={{ __html: this.state.snippet }} />
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

If you want to display obj.snippet in a div with a specified id, this would be as simple as

HTML

<div id="myDiv"></div>

JS

document.getElementById('myDiv').innerHTML = obj.snippet;
Nick
  • 16,066
  • 3
  • 16
  • 32