thatgibbyguy thatgibbyguy - 5 months ago 8
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 < this.data.stations.length; i++) {
stationsArr.push(
<div className="station">
{this.data}
</div>
)
}


And then render

render(){
return (
{stationsArr}
)
}


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

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

Answer

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 = this.props.stations.map(function(station) {
            return <div className="station">{station.call}</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.

https://jsfiddle.net/69z2wepo/14377/