ReactJS convert HTML string to JSX

298,317

Solution 1

By default, React escapes the HTML to prevent XSS (Cross-site scripting). If you really want to render HTML, you can use the dangerouslySetInnerHTML property:

<td dangerouslySetInnerHTML={{__html: this.state.actions}} />

React forces this intentionally-cumbersome syntax so that you don't accidentally render text as HTML and introduce XSS bugs.

Solution 2

There are now safer methods to accomplish this. The docs have been updated with these methods.

Other Methods

  1. Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8.

    <div>{'First · Second'}</div>

  2. Safer - Use the Unicode number for the entity inside a Javascript string.

    <div>{'First \u00b7 Second'}</div>

    or

    <div>{'First ' + String.fromCharCode(183) + ' Second'}</div>

  3. Or a mixed array with strings and JSX elements.

    <div>{['First ', <span>&middot;</span>, ' Second']}</div>

  4. Last Resort - Insert raw HTML using dangerouslySetInnerHTML.

    <div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

Solution 3

I recommend using Interweave created by milesj. Its a phenomenal library that makes use of a number if ingenious techniques to parse and safely insert HTML into the DOM.

Interweave is a react library to safely render HTML, filter attributes, autowrap text with matchers, render emoji characters, and much more.

  • Interweave is a robust React library that can:
    • Safely render HTML without using dangerouslySetInnerHTML.
    • Safely strip HTML tags.
    • Automatic XSS and injection protection.
    • Clean HTML attributes using filters.
    • Interpolate components using matchers.
    • Autolink URLs, IPs, emails, and hashtags.
    • Render Emoji and emoticon characters.
    • And much more!

Usage Example:

import React from 'react';
import { Markup } from 'interweave';

const articleContent = "<p><b>Lorem ipsum dolor laboriosam.</b> </p><p>Facere debitis impedit doloremque eveniet eligendi reiciendis <u>ratione obcaecati repellendus</u> culpa? Blanditiis enim cum tenetur non rem, atque, earum quis, reprehenderit accusantium iure quas beatae.</p><p>Lorem ipsum dolor sit amet <a href='#testLink'>this is a link, click me</a> Sunt ducimus corrupti? Eveniet velit numquam deleniti, delectus  <ol><li>reiciendis ratione obcaecati</li><li>repellendus culpa? Blanditiis enim</li><li>cum tenetur non rem, atque, earum quis,</li></ol>reprehenderit accusantium iure quas beatae.</p>"

<Markup content={articleContent} /> // this will take the articleContent string and convert it to HTML markup. See: https://milesj.gitbook.io/interweave


//to install package using npm, execute the command
npm install interweave

Solution 4

npm i html-react-parser;

import Parser from 'html-react-parser';

<td>{Parser(this.state.archyves)}</td>

Solution 5

For those still experimenting, npm install react-html-parser

When I installed it it had 123628 weekly downloads.

import ReactHtmlParser from 'react-html-parser'

<div>{ReactHtmlParser(htmlString)}</div>
Share:
298,317

Related videos on Youtube

Peter Wateber
Author by

Peter Wateber

Updated on July 08, 2022

Comments

  • Peter Wateber
    Peter Wateber almost 2 years

    I'm having trouble dealing with facebook's ReactJS. Whenever I do ajax and want to display an html data, ReactJS displays it as text. (See figure below)

    ReactJS render string

    The data is displayed through the success callback function of the jquery Ajax.

    $.ajax({
       url: url here,
       dataType: "json",
       success: function(data) {
          this.setState({
               action: data.action
          })
       }.bind(this)
    });
    

    enter image description here

    Is there any easy way to convert this into html? How should I do it using ReactJS?

  • Sophie Alpert
    Sophie Alpert over 10 years
    This syntax is shown on the homepage and in the tutorial, but I just realized it's not documented anywhere else so I just filed #413 to fix.
  • Peter Wateber
    Peter Wateber over 10 years
    Correct! I've solved this already using dangerouslySetInnerHTML but thanks though :)
  • ericn
    ericn over 8 years
    I've ready the documentation but about a long HTML string such as one from a WYSIWYG editor? I can't see how we can use the 1st, 2nd or 3rd method
  • dvdplm
    dvdplm over 8 years
    I agree with @eric. What good are methods 1-3 for already escaped content stored somewhere, e.g. a DB? Also note that method 4 – the only method – means you can't add child nodes.
  • regularmike
    regularmike over 8 years
    Yup. These examples with hard-coded "dynamic" content don't make a lot of sense.
  • Vipin Verma
    Vipin Verma about 8 years
    This is my innerHTML - "Displaying admins \u003cb\u003e1\u0026nbsp;-\u0026nbsp;10\u003c/b\u003e of \u003cb\u003e13\u003c/b\u003e in total" while this is what is being rendered - "Displaying admins <b>1&nbsp;-&nbsp;10</b> of <b>13</b> in total". When I try to use dangerouslySetInnerHTML, evrything breaks.
  • Laurent Van Winckel
    Laurent Van Winckel over 7 years
    Unfortunately document doesn't work on server rendering.
  • El Anonimo
    El Anonimo over 5 years
    Could you provide a usage example please?
  • Arman Nisch
    Arman Nisch over 5 years
    @ElAnonimo I have added a usage example. Hope that makes things a bit more clearer.
  • Nicholas Hamilton
    Nicholas Hamilton about 5 years
    Thanks a million, interweave is exactly what I needed. Cheers.
  • Coty Embry
    Coty Embry about 5 years
    It might if you do import JSDOM from 'jsdom'; global.window = new JSDOM('', { url: 'http://localhost' }); global.document = global.window.document; idk goodluck
  • Tarun Kolla
    Tarun Kolla almost 5 years
    The documentation for this is not helpful. Also I tried out with few lines of html and I had a page full of error messages. Do someone have examples or any resources with documentation?
  • Barry Michael Doyle
    Barry Michael Doyle over 4 years
    It's worth playing it safe to sanitize the content using the sanitize function from the dompurify npm package if you're getting that information from an external API.
  • Christophe
    Christophe over 3 years
    Do you know what threats Interweave does NOT cover?
  • Martin Melichar
    Martin Melichar over 3 years
    And where is the JSX?
  • Micros
    Micros over 3 years
    The latest version of this library provides a very clean way of injecting html. And the replace method is a great way to replace (for example) img tags with your own <Image/> components.
  • Peter Gerdes
    Peter Gerdes almost 3 years
    Note that despite it being 'dangerous' if you are merely using it to render html from your server it's no more dangerous than displaying that content in a webpage. The danger arises if that content has user provided input that hasn't been sanitized and if it's direct from the server you should have already sanitized in back end.
  • Sunil Kumar
    Sunil Kumar over 2 years
    You can try the easiest solution stackoverflow.com/questions/19266197/…
  • sai vineeth
    sai vineeth over 2 years
    const samplehtml = "<h1>Microsoft <abbr title=\"Operating System\">OS</abbr></h1>" const Windows = <React.Fragment>{samplehtml}</React.Fragment> This is not working
  • Gangula
    Gangula over 2 years
    even samplehtml is a JSX variable, so you need to enclose that with <React.Fragment> as well - like this: const samplehtml = <React.Fragment><h1>Microsoft <abbr title="Operating System">OS</abbr></h1></React.Fragment>
  • sai vineeth
    sai vineeth over 2 years
    I made suggested changes but still html is rendered as string
  • Gangula
    Gangula over 2 years
    you probably have a syntax error. You should not surround a JSX variable with quotes and you should not escape quotes in your<abbr /> tag as well. Copy the samplehtml variable from above comment.
  • sai vineeth
    sai vineeth over 2 years
    samplehtml is html coming from database so it is surrounded by quotes I want convert htmlstring coming from database to jsx
  • Gangula
    Gangula over 2 years
  • Gangula
    Gangula over 2 years
    Actually, your use case needs a different approach - since you're fetching the HTML from a database, you need to parse it either using a HTML Parser or use dangerouslySetInnerHTML
  • sai vineeth
    sai vineeth over 2 years
    Actually I didn't want use other libraries , Using react API is there any way to parse html string to React JSX?
  • sai vineeth
    sai vineeth over 2 years
    dangerouslySetInnerHTML is danger so thats my last resort
  • sai vineeth
    sai vineeth over 2 years
    I am getting Blog content from Database putting it inside span may effect SEO
  • Gangula
    Gangula over 2 years
    I'm afraid I'm not aware of any other way. Also you have concerns are not exactly related to this question. So I suggest you to post a new question mentioning all you concerns which would get the right folks to provide you an answer.
  • sai vineeth
    sai vineeth over 2 years
    Actually I am in correct question- ReactJS convert HTML string to JSX, that is what I want converting html in string to JSX
  • Ryan Carville
    Ryan Carville about 2 years
    Interweave works great for us. Thanks for the rec!
  • sk215
    sk215 about 2 years
    stackoverflow.com/questions/70981011/… I asked this question, any help would be appreciated