1

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.

1
  • You probably shouldn't need to go from JSX string to the DOM like that. If you elaborate on your use case, someone here might have a cleaner suggestion. Commented Jan 17, 2016 at 21:30

2 Answers 2

2

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);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.