Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a small react page that should compile and display html string. the html in the string written in react-foundation

The page looks like this :

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Link, Button, Colors } from 'react-foundation';
require('./foundation.css')

var htmlFromApi = '<div className="button-basics-example"><Button color={Colors.SUCCESS}>Save</Button><Button color={Colors.ALERT}>Delete</Button></div>';

var App = ({ html }) => { return <div>{html}</div> }

ReactDOM.render(
<App html={htmlFromApi}/>,
document.getElementById('react')
);

The Result of the above code is just a string, I am wondering if there is a way to convert the html string to react element

something like this :

var reactElement= toReactElement(htmlFromApi);
//the result is <div className="button-basics-example"><Button color={Colors.SUCCESS}>Save</Button><Button color={Colors.ALERT}>Delete</Button></div>

PS I tried <div className="content" dangerouslySetInnerHTML={{ __html: htmlFromApi }}></div> and didn't work

Thanks in advance

Edit: the code is here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
266 views
Welcome To Ask or Share your Answers For Others

1 Answer

I originally provided an answer as to how you can insert a string as HTML directly into React. However, since you also want variables inside your string to be parsed (and other potential logic) before it being inserted into React, I have left both options here as they might be useful for future readers.


Case 1 - Your string is ready to be inserted

If the string containing your HTML is ready to be directly inserted into React, and does not contain code that needs to be parsed first, you should use dangerouslySetInnerHTML. You should set it on the wrapping div that will contain the HTML fetched from your API.

See the example below.

var htmlFromApi = '<div className="button-basics-example"><Button color={Colors.SUCCESS}>Save</Button><Button color={Colors.ALERT}>Delete</Button></div>';

var App = ({html}) => { return <div dangerouslySetInnerHTML={{ __html: html}}></div> }

ReactDOM.render(<App html={htmlFromApi}/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="app"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...