Displaying static data
"Awesome! Looks good. Now, let's change our table that is displaying static information, to start fetching and displaying this information in the rows from the JSON data that we had before."
"We'll define this data in the render method itself and see how we would be using it to create our table. We'll basically just be looping over the data and creating elements, that is, table rows in our case, for the individual data set of events. Something like this:"
… var data = [{ "when": "2 minutes ago", "who": "Jill Dupre", "description": "Created new account" }, { "when": "1 hour ago", "who": "Lose White", "description": "Added fist chapter" }, { "when": "2 hours ago", "who": "Jordan Whash", "description": "Created new account" }]; var rows = data.map(function(row){ return <tr> <td>{row.when}</td> <td>{row.who}</td> <td>{row.description}</td> </tr> }); …
"Notice how we are using {}
here. {}
is used in JSX to embed dynamic information in our view template. We can use it to embed the JavaScript objects in our views, for example, the name of a person or heading of this table. As you can see, what we are doing here is using the map
function to loop over the dataset that we have. Then, we are returning a table row, constructed from the information available from the row object – the details about when the event was created, who created it and event description."
"We are using JSX syntax here to construct the rows of table. However, it is not used as the final return value from render function."
"That's correct, Shawn. React with JSX allows us to arbitrarily create elements to be used in our views, in our case, creating it dynamically from the dataset that we have. The rows variable now contains a part of view that we had used at a different place. We can also build another component of the view on top of it."
"That's the beauty of it. React allows us to dynamically create, use, and reuse the parts of views. This is helpful to build our views, part by part, in a systematic way."
"Now, after we are done with building our rows, we can use them in our final render call."
"So now, the return statement will look something similar to the following:"
… return <table> <thead> <th>When</th> <th>Who</th> <th>Description</th> </thead> {rows} </table> …
"Here's how the complete render method now looks after building up rows with static data:"
render: function(){ var data = [{ "when": "2 minutes ago", "who": "Jill Dupre", "description": "Created new account" }, { "when": "1 hour ago", "who": "Lose White", "description": "Added fist chapter" }, { "when": "2 hours ago", "who": "Jordan Whash", "description": "Created new account" }]; var rows = data.map(function(row){ return <tr> <td>{row.when}</td> <td>{row.who}</td> <td>{row.description}</td> </tr> }) return <table> <thead> <th>When</th> <th>Who</th> <th>Description</th> </thead> {rows} </table>}
"That's starting to look like where we want to reach."