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:
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:
import parse from 'html-react-parser';
import ReactHtmlParser from 'react-html-parser';
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?
question from:
https://stackoverflow.com/questions/65843853/how-can-i-parse-a-string-containing-jsx-into-jsx-components 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…