Mohammed Safeer Mohammed Safeer - 1 year ago 109
React JSX Question

How to render HTML Template and bind data from JSON response in ReactJS?

I have to render an HTML template using reactjs. HTML template is dynamic and get through an API call. There is provision in template to bind the data in html.
Sample HTML template is as follows,

<a target="_blank" href="{ad.url}">
<div class="ads temp-1">
<div class="adv-content">
<div class="advs-image">
<img src="{ad.image}" />
<div class="adv-desc">{ad.description}</div>

is an Object which contains the properties

Object is as follows,

var ad = {
"image": "testimage.jpg",
"url": "http: //",
"name": "testadvertisement",
"description": "testdescription"

I have achieved this in AngularJs using,

Now I want to move this to reactjs.
I have tried to render using reactjs
function, But it didn't help. It renders html as string.

Is there any compile like function in reactjs ? Or could you please suggest any other way to do this right way ?

Any help appreciated.

Answer Source

As I correctly undestand you should use dangerouslySetInnerHTML prop.

For example:

// SomeComponent.js

// other methods...

render() {
  // `htmlFromResponse` is your plain html string from response.
  return (
    <div dangerouslySetInnerHTML={{ __html: htmlFromResponse }} />

Using this prop, you can render plain html string into div element.

If you are getting html template from server, and want to pass variable to it before rendering, you can do it with Mustache package:

import Mustache from 'mustache';

// template should contain variables in {{ ... }}
const html = Mustache.render(htmlFromServer, {
  variable: 'value'

Next, you can render output html using dangerouslySetInnerHTML prop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download