How can I Parse a string containing JSX into JSX components

903 Views Asked by At

I am currently trying to parse a string that contains JSX into literal JSX,and inject it into the return of my component:

import react from "react";
import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles(theme => ({
  heading:{
    color: theme.palette.secondary.dark
  },
});

const Foo = () => {
  const classes = useStyles();

  const jsxString = "<span>foo <span className={classes.heading}>bar</span></span>"
  // convert or parse jsxString into literal JSX that can be rendered or returned
  // by the component.
  const jsxReact = ConvertToWhatReactUnderStands(jsxString) 
  return (
    <>
      {jsxReact}
    </>
  ); 
};

export default Foo;

I am using create-react-app, and I am not intending on ejecting.

I have tried the following:

  1. dangerouslySetInnerHTML and this does not work, when inspecting the the element I get:
<span>foo <span className="{classes.heading}">bar</span></span>

How do I go about achieving this, making sure that my styles are applied?

Also, the inner html <span/> tag was a Material-UI <Typography/> component, I had to change it because parsing it changed the component name to : <typography/> after using the following functions from these packages:

  1. import parse from 'html-react-parser';
  2. import ReactHtmlParser from 'react-html-parser';
  3. import Parser from 'html-react-parser'

and the following construct dangerouslySetInnerHTML

I understand that , I would have to transpile/transform the JSX string into javascript code with something like Babel before I execute it.

For example, when using the browser version of Babel:

var jsCode = babel.transform(jsxString);
eval(jsCode.code);

But ejecting and using Babel is not an option for me. To be breif, my question is how would I convert a string into JSX and make sure that my style Classes are are applied? Is it possible without using babel?

0

There are 0 best solutions below