Ad

Programmatically Generated JSX String

- 1 answer

I have a text file that I'd like to convert to a JSX string using Regex and display on the browser as if it's a JSX markup manually entered in the render return () block.

Let's say I create a string

generatedString = '<span class="tag" style={divStyle}>Test string</span>' 

and want to have it displayed in the browser by

render() {
  <div> {generatedString} <div>
}

The browser shows

"<span_class="tag"_style={divStyle}>Test string</span>"

as a text string, instead of "Test string" with the style applied to it.

Ad

Answer

You can use the dangerouslySetInnerHTML property on the div tag to render HTML as you like. This would still however be just displayed as HTML and not as a jsx tag, like this:

render() {
    return <div dangerouslySetInnerHTML={generatedString} />;
}

If you anyhow generate the JSX string yourself, then why not choose create a class that renders those properties, like in the following fiddle

var GeneratedComponent = React.createClass({
    propTypes: {
        content: React.PropTypes.object
    },
    render() {
        var content = this.props.content;
        if (!content || !content.tag) {
            return null;
        }
        return React.createElement(content.tag, content);
    }
});
Ad
source: stackoverflow.com
Ad