If you compile to React and encounter a JSX node with tag "div" you should compile that into React.createElement("div",... call with attributes and subnodes found under that AST node inserted as parameters of that call. So you need somekind of AST parser like espree supporting JSX and then you can create a code which walks the AST tree and outputs something, like React -code out of it. If we are very strict, this actually is the valid JSX. The question is how to compile this JSX string into React code.
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
You can consider using the React attribute dangerouslySetInnerHTML
:
class YourComponent{
render() {
someHtml = '<div><strong>blablabla<strong><p>another blbla</p/></div>'
return (
<div className="Container" dangerouslySetInnerHTML={{__html: someHtml}}></div>
)
}
}
Just for an alternative, nowadays there is a library called react-html-parser. You can check it and install from NPM registry at this URL: https://www.npmjs.com/package/react-html-parser. Today's weekly download statistic for that package is 23,696. Looks a quite popular library to use. Even it looks more convenient to use, my self, still need more read and further consideration before really using it.
Code snippet copied from the NPM page:
import React from 'react';
import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 } from 'react-html-parser';
class HtmlComponent extends React.Component {
render() {
const html = '<div>Example HTML string</div>';
return <div>{ ReactHtmlParser(html) }</div>;
}
}
We were able to demonstrate how to correct the How To Convert Html String To Jsx Element bug by looking at a variety of examples taken from the real world. There are a variety of approaches that can be taken to solve the same problem How To Convert Html String To Jsx Element. The remaining options will be discussed further down. How To Convert Html String To Jsx Element With Code Examples JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods. JSX converts HTML tags into react elements.
Hello everyone, In this post, we will examine how to solve the How To Convert Html String To Jsx Element problem using the computer language.
import React from "react";
export default function App() {
return <div dangerouslySetInnerHTML={{ __html: "First · Second" }} />;
}
import React from "react";
export default function App() {
return <div>{["First ", <span key="1">·</span>, " Second"]}</div>;
}
import React from "react";
export default function App() {
return <div>{"First Second"}</div>;
}
So you have an HTML string like this: How to convert raw HTML into React element with third party libraries like html-react-parser. We will need a parser that is able to take the HTML string as an input and give out React elements as output. There are a few options (third party packages) that we can use: Really easy to use! Will these libraries sanitize the HTML ? Check their documentation but html-react-parser for instance does not. Hence if you need sanitization then feel free to use DOMPurify.sanitize(htmlString) here as well.
const htmlString = `
<div data-library="react">
<h1 data-type="heading">Hello</h1>
<p>React!</p>
</div>
`;
And you want to convert it into React elements. Of course in JSX if we just replace the backticks (`...`
) with parentheses ((...)
), we will automatically get the React element object tree assigned to htmlString
. But we’re talking about cases where you got a plain/raw HTML string from somewhere and would want to convert that to one or more React elements. Let’s talk a bit about rendering raw HTML and then we’ll come back to the conversion.
If we only wanted to render the HTML string, we could make use of the dangerouslySetInnerHTML
feature.
function Component() {
const htmlString = '...';
return <div dangerouslySetInnerHTML={__html: htmlString} />;
}
The component above would return and render a React element representing a div
with the htmlString
shoved inside it as children. The feature or property name to inject the raw HTML string is dangerouslySetInnerHTML
because injecting HTML directly into your webpage can be vulnerable to XSS attacks. Basically if the HTML was coming from an untrusted source, it could contain malicious JavaScript code that would run on the user’s browser with the ability to cause havoc.
Can we solve the XSS problem ? There’s a library called DOMPurify that we could use to sanitize the HTML string before rendering it.
import DOMPurify from 'dompurify';
function Component() {
const htmlString = ...;
return <div dangerouslySetInnerHTML={__html: DOMPurify.sanitize(htmlString)} />;
}
Really easy to use! Will these libraries sanitize the HTML ? Check their documentation but html-react-parser
for instance does not. Hence if you need sanitization then feel free to use DOMPurify.sanitize(htmlString)
here as well.
The only piece of important code in the example above that does the parsing and conversion is the parse
function which returns a React element (tree). Basically:
parse('<p>Hello, World!</p>');
// returns
React.createElement('p', {}, 'Hello, World!')
Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8. <div>{'First · Second'}</div> Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8. 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> Safer - Use the Unicode number for the entity inside a Javascript string.
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)
});
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}} />
If you want to test out how some specific JSX is converted into JavaScript, you can try out the online Babel compiler. When you pass a string literal, its value is HTML-unescaped. So these two JSX expressions are equivalent: Conversely, if you want a value like false, true, null, or undefined to appear in the output, you have to convert it to a string first: Spread attributes can be useful but they also make it easy to pass unnecessary props to components that don’t care about them or to pass invalid HTML attributes to the DOM. We recommend using this syntax sparingly.
<MyButton color="blue" shadowSize={2}>
Click Me
</MyButton>
React.createElement(
MyButton, {
color: 'blue',
shadowSize: 2
},
'Click Me'
)
<div className="sidebar" />
import React from 'react';import CustomButton from './CustomButton';
function WarningButton() {
// return React.createElement(CustomButton, {color: 'red'}, null); return <CustomButton color="red" />;
}
import React from 'react';
const MyComponents = {
DatePicker: function DatePicker(props) {
return <div>Imagine a {props.color} datepicker here.</div>;
}
}
function BlueDatePicker() {
return <MyComponents.DatePicker color="blue" />;}
The reason why your HTML attributes aren't getting called is because inline event handlers (e.g., onclick) are parsed as a string rather than a function. See #73. HTML to React parser that works on both the server (Node.js) and the client (browser): The parser converts an HTML string to one or more React elements. Tags are lowercased by default. To prevent that from happening, pass the htmlparser2 option:
const parse = require('html-react-parser');
parse('<p>Hello, World!</p>'); // React.createElement('p', {}, 'Hello, World!')
npm install html - react - parser--save
<!-- HTMLReactParser depends on React -->
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/html-react-parser@latest/dist/html-react-parser.min.js"></script>
<script>
window.HTMLReactParser( /* string */ );
</script>
// ES Modules
import parse from 'html-react-parser';
// CommonJS
const parse = require('html-react-parser');