ReactJS convert HTML string to JSX
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
-
Easiest - Use Unicode, save the file as UTF-8 and set the
charset
to UTF-8.<div>{'First · Second'}</div>
-
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>
-
Or a mixed array with strings and JSX elements.
<div>{['First ', <span>·</span>, ' Second']}</div>
-
Last Resort - Insert raw HTML using
dangerouslySetInnerHTML
.<div dangerouslySetInnerHTML={{__html: 'First · 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>
Related videos on Youtube
Peter Wateber
Updated on July 08, 2022Comments
-
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)
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) });
Is there any easy way to convert this into html? How should I do it using ReactJS?
-
Sophie Alpert over 10 yearsThis 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 over 10 yearsCorrect! I've solved this already using dangerouslySetInnerHTML but thanks though :)
-
ericn over 8 yearsI'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 over 8 yearsI 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 over 8 yearsYup. These examples with hard-coded "dynamic" content don't make a lot of sense.
-
Vipin Verma about 8 yearsThis 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 - 10</b> of <b>13</b> in total". When I try to use dangerouslySetInnerHTML, evrything breaks.
-
Laurent Van Winckel over 7 yearsUnfortunately document doesn't work on server rendering.
-
El Anonimo over 5 yearsCould you provide a usage example please?
-
Arman Nisch over 5 years@ElAnonimo I have added a usage example. Hope that makes things a bit more clearer.
-
Nicholas Hamilton about 5 yearsThanks a million, interweave is exactly what I needed. Cheers.
-
Coty Embry about 5 yearsIt might if you do
import JSDOM from 'jsdom'; global.window = new JSDOM('', { url: 'http://localhost' }); global.document = global.window.document;
idk goodluck -
Tarun Kolla almost 5 yearsThe 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 over 4 yearsIt's worth playing it safe to sanitize the content using the
sanitize
function from thedompurify
npm package if you're getting that information from an external API. -
Christophe over 3 yearsDo you know what threats Interweave does NOT cover?
-
Martin Melichar over 3 yearsAnd where is the JSX?
-
Micros over 3 yearsThe 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 almost 3 yearsNote 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 over 2 yearsYou can try the easiest solution stackoverflow.com/questions/19266197/…
-
sai vineeth over 2 yearsconst samplehtml = "<h1>Microsoft <abbr title=\"Operating System\">OS</abbr></h1>" const Windows = <React.Fragment>{samplehtml}</React.Fragment> This is not working
-
Gangula over 2 yearseven
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 over 2 yearsI made suggested changes but still html is rendered as string
-
Gangula over 2 yearsyou 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 thesamplehtml
variable from above comment. -
sai vineeth over 2 yearssamplehtml is html coming from database so it is surrounded by quotes I want convert htmlstring coming from database to jsx
-
Gangula over 2 yearsTry this answer: stackoverflow.com/a/49323189/6908282
-
Gangula over 2 yearsActually, 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 over 2 yearsActually I didn't want use other libraries , Using react API is there any way to parse html string to React JSX?
-
sai vineeth over 2 yearsdangerouslySetInnerHTML is danger so thats my last resort
-
sai vineeth over 2 yearsI am getting Blog content from Database putting it inside span may effect SEO
-
Gangula over 2 yearsI'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 over 2 yearsActually I am in correct question- ReactJS convert HTML string to JSX, that is what I want converting html in string to JSX
-
Ryan Carville about 2 yearsInterweave works great for us. Thanks for the rec!
-
sk215 about 2 yearsstackoverflow.com/questions/70981011/… I asked this question, any help would be appreciated