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

2
  • i think this will help you: How to put variable in string Commented Jun 22, 2018 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 reactjs.org/docs/react-without-jsx.html Commented Jun 22, 2018 at 12:05

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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!

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.