thatgibbyguy thatgibbyguy - 1 year ago 192
Javascript Question

Rendering React Components from Array of Objects

I have some data called stations which is an array containing objects.

stations : [
{call:'station one',frequency:'000'},
{call:'station two',frequency:'001'}

I'd like to render a ui component for each array position. So far I can write

var stationsArr = []
for (var i = 0; i <; i++) {
<div className="station">

And then render

return (

The problem is I'm getting all of the data printing out. I instead want to just show a key like
but that prints nothing.

How can I loop through this data and return a new UI element for each position of the array?

Answer Source

As of current version of React, it is not possible to return multiple ReactElement items from the render function. You have to wrap them in a container (but it may change in the future).

Try the following

var Test = React.createClass({
    render: function() {
        var stationComponents = {
            return <div className="station">{}</div>;
        return <div>{stationComponents}</div>;

var stations = [
  {call:'station one',frequency:'000'},
  {call:'station two',frequency:'001'}

React.render(<Test stations={stations} />, document.getElementById('container'));

Also, try to add a unique "key" attribute to each station element.

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