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?

3
  • Possible duplicate of Rendering a string as React component Commented Sep 24, 2017 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). Commented Sep 24, 2017 at 13:46
  • Googled "react parse jsx" and got npmjs.com/package/react-jsx-parser Commented Sep 24, 2017 at 19:18

1 Answer 1

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

1 Comment

No Use. This approach doesn't work. Instead, it gives below: <testcomponent></testcomponent>

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.