Reputation: 311
Suppose I have some process that generates some JSX dynamically but as a literal string, is it possible to return it as JSX that renders imported components, Material UI in this case?
With the below I can only get unstyled markup to display.
import * as React from 'react';
import { Button } from '@material-ui/core';
export default class Testsp extends React.Component<ITestspProps, {}> {
public render(): React.ReactElement<ITestspProps> {
return <div dangerouslySetInnerHTML={this.someConvolutedProcess()} />
}
someConvolutedProcess() {
let generatedJSX = '<Button color="primary">Hello World... Again</Button>';
return {__html: generatedJSX};
}
}
With the below I have to provide element as JSX, not a string
ReactDOMServer.renderToStaticMarkup(element)
I know my approach is weird but I have a niche case
Upvotes: 0
Views: 155
Reputation: 53874
There is no built-in option to generate JSX from a string (string-to-JSX).
Note that you actually want to generate React element (React.createElement
) from a string (as JSX is only syntactic sugar)
dangerouslySetInnerHTML
accepts only HTML elements, not JSX.ReactDOMServer
is for rendering component to static markup, i.e JSX-to-string, JSX-to-HTML.Upvotes: 1