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.

4
  • What technology are you using in frontend? Commented Oct 15, 2017 at 15:53
  • 1
    @Hassan Imam's question is a good one. What you have is already valid HTML. Commented Oct 15, 2017 at 15:54
  • React. It just displays the response with tags as plain text. I want to be able to display <span> etc as html code Commented Oct 15, 2017 at 15:56
  • 1
    Possible duplicate of Render HTML string as real HTML in a React component Commented Oct 15, 2017 at 16:15

2 Answers 2

12

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>

Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.