Reputation: 3310
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.
Upvotes: 1
Views: 846
Reputation: 239
you can do it like this as well.
Create a component that returns JSX and also takes the variables through props.
const renderSpan = ({divStyle}) => {
return (
<span class="tag" style={divStyle}>Test string</span>
)
}
Then use it
<div>
{renderSpan(divStyle)}
</div>
You can pass the divStyles as an object.
Upvotes: 0
Reputation: 12806
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);
}
});
Upvotes: 2