I'm making a Gatsby site, and after running some GraphQL queries, I pass some HTML strings into React components. I've been able to render these with dangerouslySetInnerHtml, html-react-parser, etc. However, I'd like to also just write component tags within the original Markdown and render those as components.
A simple example of this would be
import React from "react";
export default function App() {
const RedDiv = () => {
return <div style={{ color: "red" }}>This is a red div</div>;
};
const StringRedDiv = "<div style={{color: 'red'}}>This is a red div</div>";
return (
<div className="App">
<RedDiv />
<div dangerouslySetInnerHTML={{ __html: StringRedDiv }} />
</div>
);
}
CodeSandbox
Obviously, we don't need to use dangerouslySetInnerHtml here, but I'd like to achieve the desired effect (in this case having both divs have red text) using a method which takes an HTML string and transforms it into React.
For that, you can use the react-html-parser like this:
import React from 'react';
import ReactHtmlParser from 'react-html-parser';
class HtmlComponent extends React.Component {
render() {
const html = "<div style={{color: 'red'}}>This is a red div</div>";
return <div>{ ReactHtmlParser(html) }</div>;
}
}
On a side note, in order for the dangerouslySetInnerHTML or alternatively the ReactHtmlParser to work, you must use valid HTML attributes.
For instance, the style attribute in your example:
<div style={{color: 'red'}}>This is a red div</div>
should be changed to:
<div style="color: red;">This is a red div</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With