Mohammed Safeer Mohammed Safeer - 4 months ago 16
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">
<h2>{ad.name}</h2>
<div class="adv-content">
<div class="advs-image">
<img src="{ad.image}" />
</div>
<div class="adv-desc">{ad.description}</div>
</div>
</div>
</a>


Here
ad
is an Object which contains the properties
url
,
image
,
name
,
description
etc

Sample
ad
Object is as follows,

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


I have achieved this in AngularJs using,
$compile
service.

Now I want to move this to reactjs.
I have tried to render using reactjs
render
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

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.