Home > Mobile >  How to sanitized HTML in React?
How to sanitized HTML in React?

Time:11-12

I am trying to display HTML content on React front side.

What is input

<p>Hello/<p>

Aadafsf

<h1>H1 in hello</h1>


I write this from CKEditor from Admin side

What I got in React Front side?

<p>Hello/<p>

Aadafsf

<h1>H1 in hello</h1>

It should be like

Hello

Aadafsf

H1 in hello


What I used?

import {Parser} from "html-to-react";
import DOMPurify from "dompurify";

{Parser().parse(DOMPurify.sanitize(HTMLCONTENT))}

enter image description here

I tried this but I'm not getting the expected output.

Used dangerouslySetInnerHTML

HTML CONTENT

<h2>This is Heading</h2><p>&lt;p&gt;&lt;/p&gt;</p><p>This is para.</p><p>&nbsp;</p><p><strong>This is Bold</strong></p><p>&nbsp;</p><ol><li><strong>dwsfdf</strong></li><li><strong>fdsfdf</strong></li></ol><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><figure class="media"><oembed url="https://youtu.be/rokGy0huYEA"></oembed></figure>
<div dangerouslySetInnerHTML={{__html: HTMLCONTENT}} />;

CodePudding user response:

You could allow some tags you want like this

let clean = DOMPurify.sanitize('<div>hello</div>',{ALLOWED_TAGS: ['b', 'q'], ALLOWED_ATTR: ['style']});

CodePudding user response:

It seems that what you actually want is to set raw HTML in your component.

React offer this possibility with dangerouslySetInnerHTML.

That said take real care as this can open your site to attacks known as cross-site scripting (XSS).

  • Related