Skip to content Skip to sidebar Skip to footer

Convert String To React Jsx

Goal: I want to convert strings including React components into fully-functional JSX. The easier example, for which there are many solutions on Stack Overflow, is this: render() {

Solution 1:

There is no library which parses a string containing custom React component.

If you think about it, such library needs to be aware of your components locations as it needs to import and render it. Moreover, the actual name of the components is meaningless in React, you must have its instance available in scope.

Therefore your only solution is to write a custom parser for your own.

Such solution will roughly hold a dictionary which maps string to their components (need to handle props and duplicate naming too).

import {MyComponent,Button} from'components';

exportconstComponents = {
   MyComponent,
   Button
};

myParser('<MyComponent/>'); // Match MyComponent

You can use ReactDOMServer hence you have the element instance to render its HTML.

Solution 2:

You can use -

  • html-react-parser
  • react-jsx-parser

Post a Comment for "Convert String To React Jsx"