Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying pure html in react

I playing with react-draft-wysiwyg editor. I progress quite well. But now I stuck how can I display the output of the editor.

For example, let suppose body is the output of the wysiwyg editor:

function ShowHtml(props) {
  let body = '<p>Sample text with <strong>bold</strong> and <em>italic</em></p>'
  return (
    <div>
     {body}
    </div>
  )
}

Now the output will be exactly the same html with tags displayed without formatting.

<p>Sample text with <strong>bold</strong> and <em>italic</em></p>

And I would like something like this:

Sample text with bold and italic

In jQuery I would just set the html property of the div tag. But I do not know how to do it the proper way in React. Can I just grab a reference to the div and update it somehow just like in jQuery? Is it working with the virtual Dom?

like image 767
Peter Ambruzs Avatar asked Mar 21 '18 08:03

Peter Ambruzs


People also ask

How do I display HTML content in react JS?

React's goal is in many ways to render HTML in a web page. React renders HTML to the web page by using a function called ReactDOM. render() .

Can I use normal HTML in React?

The HTML could be from an external source or a file that you want to display to the user. By default, React does not permit you to inject HTML in a component, for various reasons including cross-site scripting. However, for some cases like a CMS or WYSIWYG editor, you have to deal with raw HTML.

How do you render external HTML file in react JS?

Fetching the HTML from an external source One simple way to do dynamically fetch a choose a specific file would be to let your backend (e.g php) read the file from a local folder, parse the text, and send it back through an AJAX request.


1 Answers

try to insert as an attribute dangerouslySetInnerHTML={{__html: body}}

  function ShowHtml(props) {
    let body = '<p>Sample text with <strong>bold</strong></p>'
    return (
     <div  dangerouslySetInnerHTML={{__html: body}} />
    )
  }

https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

like image 179
Pablo Avatar answered Oct 22 '22 13:10

Pablo