Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a HTML string in React?

Tags:

reactjs

I have a string like < b >hi< /b >. I have to render it as "hi". Can someone let me know an equivalent thing like innerHTML in Angular that I can use in React?

like image 522
Kousika Ganesan Avatar asked Nov 25 '17 08:11

Kousika Ganesan


People also ask

Can React render HTML file?

If you try to render an HTML string inside a component directly, React will automatically sanitize it and render it as a plain string.

How convert HTML to text in react JS?

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.

Can react native render HTML?

Using react-native-render-html This one is another package you can add to your React Native project for displaying HTML content. It is introduced as an iOS/Android pure javascript react-native component that renders your HTML into 100% native views.


4 Answers

you can try dangerouslySetInnerHTML with the enclosing tag:

      <div dangerouslySetInnerHTML={{ __html: yourhtml }} />
like image 129
Jeffin Avatar answered Oct 01 '22 15:10

Jeffin


According to official React docs

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous. For example:

function createMarkup() {
  return {__html: 'First &middot; Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}
like image 45
Abhinav Singi Avatar answered Oct 05 '22 15:10

Abhinav Singi


To avoid the potential security vulnerabilities (such as XSS attacks) that are present when using dangerouslySetInnerHTML, you can do the following:

First use DOMPurify to clean the HTML.

import DOMPurify from 'dompurify';

let clean = DOMPurify.sanitize(dirtyHtmlString, {USE_PROFILES: {html: true}});

Then it can be rendered using react-render-html as Salman Lone said:

import renderHTML from 'react-render-html';

<div>
   {renderHTML(clean)}
</div>
like image 29
Isoaxe Avatar answered Oct 03 '22 15:10

Isoaxe


in my case, I used following pacakge.

react-render-html

like image 42
Salman Lone Avatar answered Oct 04 '22 15:10

Salman Lone