render html in state string
Use dangerouslySetInnerHTML
to inject HTML as a string in React (but note that React won’t be able to use this markup in its virtual DOM):
<div dangerouslySetInnerHTML={{__html: this.state.output}} />
http://jsfiddle.net/5Y8r4/11/
The API for doing this is deliberately complex because this isn't safe to do routinely. React has protections against XSS, using dangerouslySetInnerHTML
circumvents those and opens you up to risk if you aren't sanitizing that data.
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 a dom node because isn't escaped
ReactJS convert HTML string to JSX
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.
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"]
}}
/>
);
};
Render HTML entities inside a string in React
Using the String.fromCharCode
method:
Check React docs : https://shripadk.github.io/react/docs/jsx-gotchas.html
MDN Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode
To Find the char code: http://www.mauvecloud.net/charsets/CharCodeFinder.html
render() {
return (
<h4>
{theme == 'blue' && 'This is sample text'}
{theme == 'red' && `What ${String.fromCharCode(8217}s your role in this project`}
</h4>
)
}
template literals `` for the text
render() {
return (
<h4>
{theme == 'blue' && 'This is sample text'}
{theme == 'red' && `What’s your role in this project`}
</h4>
)
}
Using double quotes and single quotes
render() {
return (
<h4>
{theme == 'blue' && 'This is sample text'}
{theme == 'red' && "What’s your role in this project"}
</h4>
)
}
Use escape character
return (
<h4>
{theme == 'blue' && 'This is sample text'}
{theme == 'red' && 'What \’s your role in this project'}
</h4>
)
}
React - pass props/state to rendered HTML string?
If what you have in mind is to send down a React component (in JSX syntax) from your server to your client and have the client somehow rehydrate/compile it into an actual, working component, this is not achievable that easily.
When you build and bundle your React app, only components that are statically referenced/imported in your application at compile time can be used at runtime on the browser.
So, in order to dynamically render a component from a template and embed variables into it, your choices are:
Render it into final HTML on your server, send down that HTML and have a simple React component perform
dangerouslySetInnerHTML
for it. But, like you've already observed, that content has to be the full HTML code, no templates, variables, JSX, etc. Everything is string and HTML at this point, no more processing.Alternatively, send down a Markdown document and have a Markdown component parse it into HTML and display it.
Create a sophisticated component that can receive a string, parse it, tokenize it, substitute values in it, etc. Essentially, create your own template-processing component that can read a template (the string sent down from your server) and embed the appropriate values into it.
A simple solution (to substitute values into a template) would be:
function Filler(props) {
let html = props.template;
Object.keys(props).forEach(key => {
if (key !== "template")
html = html.replace("{" + key + "}", props[key]);
});
return <div dangerouslySetInnerHTML={{__html: html}} />;
}
and use it like
<Filler template={"<h1>Hello, {firstname} {lastname}</h1>"} firstname="John" lastname="Doe" />
But again, this is far from a full-fledged actual React component.
Related Topics
Can You Determine If Chrome Is in Incognito Mode via a Script
What Advantages Does Using (Function(Window, Document, Undefined) { ... })(Window, Document) Confer
Replace a Regex Capture Group with Uppercase in JavaScript
JavaScript Syntax (0, Fn)(Args)
How to Terminate the Script in JavaScript
Url Encode a String in Jquery for an Ajax Request
Origin <Origin> Is Not Allowed by Access-Control-Allow-Origin
How to Swap Two Variables in JavaScript
Http Status Code 401 Even Though I'm Sending Credentials in the Request
How to Sequentially Run Promises with Q in JavaScript
Access JavaScript Nested Objects Safely
Format Date in a Specific Timezone
How to Detect If Flash Is Installed and If Not, Display a Hidden Div That Informs the User
Obtain Form Input Fields Using Jquery
Jquery Pass More Parameters into Callback
How to Detect Escape Key Press with Pure Js or Jquery
JavaScript Extract Certain Properties from All Objects in Array