Rendering Raw HTML with Reactjs

Rendering raw html with reactjs

You could leverage the html-to-react npm module.

Note: I'm the author of the module and just published it a few hours ago. Please feel free to report any bugs or usability issues.

How to render raw HTML content to React pass via props?

Try the dangerouslySetInnerHTML attribute :

 <Fragment key={propId}>
<div dangerouslySetInnerHTML={ { __html: data.htmlContent}} >

</div>
</Fragment>

Render raw HTML inside a react div

You can use dangerouslySetInnerHTML to achieve this.

const style = {
border: '2px solid #eee',
height: '270px',
width: '100%',
overflow: 'auto',
padding: '10px'
}

const test = () => {
const [contentFromDB, setContentFromDB] = useState("");

useEffect(() => {
async function fetchData() {
setContentFromDB(await myAPI.getData())
}
}, []);

return (
<>
<div className="row">
<h3>Test Render</h3>
<div style={style}>
<div dangerouslySetInnerHTML={{__html:contentFromDB}} />
</div>
</div>
</>
)
}

export default test;

How to render HTML from database in react?

You need to set the response.data to a component state using useEffect hook and then render the HTML string using dangerouslySetInnerHTML property.

Try like below.

import React, { useState, useEffect } from "react";
import axios from "axios";
// import {renderWebpage} from "../actions/webpage"
type HTMLData = {
content: { "mycustom-html": string };
};

export const Page: React.FC = () => {
const [htmlData, setHtmlData] = useState<HTMLData>({
content: { "mycustom-html": "<p>demo</p>" }
});

const renderWebpage = () => {
axios
.get("http://localhost:8080/61ea7fd2268f37443ca4d59a")
.then((response) => {
console.log("response", response);
console.log(response.data, "data");
setHtmlData(response.data);
});
};

useEffect(() => {
renderWebpage();
}, []);

return (
<div
dangerouslySetInnerHTML={{
__html: htmlData?.content?.["mycustom-html"]
}}
/>
);
};

How to render HTML string as real HTML?

Check if the text you're trying to append to the node is not escaped like this:

var prop = {
match: {
description: '<h1>Hi there!</h1>'
}
};

Instead of this:

var prop = {
match: {
description: '<h1>Hi there!</h1>'
}
};

if is escaped you should convert it from your server-side.

The node is text because is escaped

The node is text because is escaped

The node is a dom node because isn't escaped

The node is a dom node because isn't escaped



Related Topics



Leave a reply



Submit