Published on: 17 August, 2016

How to populate JSON data using ReactJS framework.

Posted by andy | 2012 views 0 likes 1 favourites 2 comments
Tumblr Digg Google Plus

In this tutorial you will learn how to populate JSON data using React JS framework. The first step is to import the required react js framework scripts. We source the scripts from the CDN directly.

<script src="http://fb.me/react-0.13.0.js"></script>
<script src="http://fb.me/JSXTransformer-0.13.1.js"></script>

The JSXTransformer script is used if we want to return in HTML Tag format in React, so this is optional. I would recommend to use this as it will be easier to read.

Here is the simple example of code on how to populate JSON data into a table rows using React JS framework.

<div id="divContent"></div>
<script type="text/jsx">
	var SampleReact = React.createClass({
		render: function(){
			var data = 	[
				{ 
					"name": "James Angus", 
					"age" : "22", 
					"job": "Dentist" 
				},
				{ 
					"name": "Milan Howen", 
					"age" : "36", 
					"job": "Truck Driver" 
				}	
			];

			var rows = data.map(function(row){
			 return <tr>
					 <td>{row.name}</td>
					 <td>{row.age}</td>
					 <td>{row.job}</td>
				 </tr>
			 });
			 
			return  <table>
						<thead>
						<th>Name</th>
						<th>Age</th>
						<th>Job</th>
						</thead>
						{rows}
					</table>
						
		}
	});
	
	React.render(React.createElement(SampleReact), document.getElementById("divContent"));
</script>

Notes

When returning the final render value, it has to be wrapped in a minimum of one html tag. So, if you just return {rows}, it will never work and you will get an error. Either you can return it as the following code:

<div>
{rows}
</div>

Just a note, the returning html tag need to be enclosed tag per line. Otherwise you will receive another error again.

Quick Demo

You can see the actual demo in the following link. Click here to see the actual demo.

Download Demo Files

Alternatively, if you prefer to work in your computer, you can download the complete source code in here. Download

Comments
Robin
Commented on: 11 Oct, 2017 04:26:42 PM
Do you have a working example of this or a code dump I can paste it in as a test to work from?
andy
Commented on: 14 Oct, 2017 07:09:19 PM
Hi Robin, I have included an example of above code in the following URL. http://bytutorial.com/assets/content/files/reactjs/populatejson/index.html I have added the download file as well on this article, so you can run it on your computer.
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.
Share your article with us and add your own google adsense account to earn extra money. Plus, you can promote a link back to your site.