Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a React Component within dangerouslySetInnerHtml or similar

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.

like image 807
Antoine Ego Avatar asked Mar 22 '26 10:03

Antoine Ego


1 Answers

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>
like image 168
Bassem Avatar answered Mar 23 '26 23:03

Bassem