Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js render text as HTML

This is how the render code looks now (And I know it's unsafe to do so):

render: function() {
  return (
    <div className="container-fluid pages_container">
      <p dangerouslySetInnerHTML={{__html: this.state.page.body}} />
    </div>
  );
}

The question is how can I render it safely?

like image 906
Fleeck Avatar asked Aug 06 '15 08:08

Fleeck


People also ask

How do you render a string as HTML in React?

To render the html string in react, we can use the dangerouslySetInnerHTML attribute which is a react version of dom innerHTML property. The term dangerously is used here to notify you that it will be vulnerable to cross-site scripting attacks (XSS).

Can I convert React to HTML?

Yes, both Angular and React apps can be (and usually are) "built" to static HTML, CSS and JS.

How convert HTML to text in ReactJS?

There're several ways to convert HTML Strings to JSX with React. One way is to put the string in between curly braces in our component. Another way is to put the string in an array with other strings or JSX code. Finally, we can use the dangerouslySetInnerHTML prop render an HTML string as HTML in our component.

Is JSX converted to HTML?

JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods. JSX converts HTML tags into react elements.


1 Answers

Reference https://facebook.github.io/react/docs/dom-elements.html#dangerouslysetinnerhtml

<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script>

render: function() {
  return (
    <div className="container-fluid pages_container">
      <p dangerouslySetInnerHTML={{__html: marked(this.state.page.body, {sanitize: true})}} />
    </div>
  );
}

jsFiddle

like image 113
Vishnu Avatar answered Oct 03 '22 05:10

Vishnu