1

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

  • i think this will help you: [How to put variable in string](https://stackoverflow.com/questions/3304014/how-to-interpolate-variables-in-strings-in-javascript-without-concatenation) – Mayank Shukla Jun 22 '18 at 11:49
  • JSX just get's transpiled to actual js code when it's built with webpack. To create components from a string dynamically you should look @ the react top-level api (Specifically `React.createElement`). See https://reactjs.org/docs/react-without-jsx.html – ZombieTfk Jun 22 '18 at 12:05

2 Answers2

1

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.

Colin Ricardo
  • 16,488
  • 11
  • 47
  • 80
0

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!