Reputation:
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.
Upvotes: 5
Views: 8342
Reputation:
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>
Upvotes: 12
Reputation: 16576
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;
Upvotes: 0