4

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?

0xdeadbeef
  • 101
  • 1
  • 5
  • Is there a specific reason why you are trying to do this? I would suggest creating a generic component that renders a different component based on props or something similar. – Basant Singh Jan 22 '21 at 11:34
  • So the idea here is to create a section on a web application based on values that are obtained from a database. These values are just strings that contain JSX elements as depicted in the example code. – 0xdeadbeef Jan 22 '21 at 11:41
  • Since you do not want to eject and use Babel at runtime, I don't see any other option. But also, IMO i don't think this is the right solution for your problem. Instead of saving JSX in the database, you should be saving some other config/data and based on that render your component. Keep the UI logic out of the backend. – Basant Singh Jan 22 '21 at 11:47
  • Thank you @basantSingh, really appreciate your feedback. I believe I will have to somehow find a way for this to work. – 0xdeadbeef Jan 22 '21 at 12:05

0 Answers0