Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

reactjs - How can I Parse a string containing JSX into JSX components

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?

question from:https://stackoverflow.com/questions/65843853/how-can-i-parse-a-string-containing-jsx-into-jsx-components

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...