2

I have some JSX format strings which are saved into the database. Now I want to convert them to the JSX again. For example:

let a = "<TestComponent />"; // String is loaded from database
ReactDOM.render(
    a,
    document.getElementById('root')
);

How could it be possible?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Mohammad Rezaei
  • 241
  • 3
  • 16
  • Possible duplicate of [Rendering a string as React component](https://stackoverflow.com/questions/36471869/rendering-a-string-as-react-component) – bennygenel Sep 24 '17 at 13:29
  • 1
    That post asks "how do I take a string and render it as content?" while this posts asks "how do I take a string and render it as the component itself?" Not a dupe (of that one, anyway). – Mike Post Sep 24 '17 at 13:46
  • Googled "react parse jsx" and got https://www.npmjs.com/package/react-jsx-parser – JulienD Sep 24 '17 at 19:18

1 Answers1

1

You can use dangerouslySetInnerHTML like this:

let a = "<TestComponent />"; // String is loaded from database
function createMarkup() {
  return {__html: a};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

ReactDOM.render(
  a,
  document.getElementById('root')
);
Rohan
  • 257
  • 1
  • 4
  • 13