James Hanson
James Hanson

Reputation: 21

How do I convert html with jsx to jsx in React.js

I want to have an API with returns HTML with JSX. When the HTML is loaded, I want to convert this to JSX and pass the props from my

Given this set of code:

import { renderToString } from "react-dom/server";
import ReactDOM from 'react-dom';

function MyHtml (props) {
    var apiHtml = renderToString("<div>{this.props.title}</div>");
    return (
        <div dangerouslySetInnerHTML={{ __html:  apiHtml }} />
    )
}
export default MyHtml;
ReactDOM.render(
    <MyHtml title="test"/>,
    document.getElementById('test')
);

I want to have the output

<div>test</div>

Instead, I get

<div>{this.props.title}</div>

Thanks

Upvotes: 1

Views: 1430

Answers (2)

James Hanson
James Hanson

Reputation: 21

I ended up doing something like this:

var { title } = this.props; // => testing
var html = ReactDOMServer.renderToString("<div>${title}</div>");
var toRender = eval('`'+html +'`');

To give the output:

<div>testing</div>

Thanks everyone!

Upvotes: 0

Colin Ricardo
Colin Ricardo

Reputation: 17239

I think what you're looking for is:

var apiHtml = renderToString(`<div>{${this.props.title}}</div>`);

Using template literals to fill in the code you want.

Upvotes: 1

Related Questions