3

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.

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that works! Out of curiosity, I also tried it when passing the string "<RedDiv/>" and that doesn't seem to work. Any idea how to make that work as well?
I don't think that's possible though, as you need to pass valid HTML (not JSX) strings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.