Yenteh Liu
Yenteh Liu

Reputation: 21

how to return the object content (JSON file) by their key through React?

I have a Json dictionary file containing several parking garages information. garage name is the key to the detail information of that garage. the data structure is like this

I am trying to write a for loop in React to pull all the garages information to my webpage in list format.

My code:

MyComponents.Garage = React.createClass({
  render: function() {
    var garage = this.props.garage
     console.log(garage)
    return (
        <li className="card-content">
        TODO: This is a component about a garage whose
        raw data is //{JSON.stringify(this.props.garage)}
          <MyComponents.GarageTitle
            title={this.props.garage.friendlyName}/>
          <MyComponents.GarageSpaces
            open={this.props.garage.open_spaces}
            total={this.props.garage.total_spaces}/>
          <MyComponents.GarageRates
            rates={this.props.garage.rates}/>
          <MyComponents.GarageHours
            hours={this.props.garage.hours}/>
        </li>
    );
  }
});
MyComponents.Garages = React.createClass({
  render: function(){
    console.log(this.props.garage)
    for (var key in this.props.garage){
      console.log(this.props.garage[key])
      return (
        <ul>
        <MyComponents.Garage garage={this.props.garage[key]}/>
        </ul>
      );
    }
  }
});

I first pass the Json data to Mycomponent.Garages and run the for loop inside and call Mycomponent.Garage for each detail information of that Garage.

But My problem is that I can only run through the first Garage, it won't keep looping the remaining Garages.

Can anyone help me with my task?

Thanks

Upvotes: 1

Views: 54

Answers (1)

polskais1
polskais1

Reputation: 186

Using return in your for in loop will not work, but you're close to getting it right! Instead, try creating an array of garages nodes:

MyComponents.Garages = React.createClass({
  render: function(){
    garageNodes = [];
    for (var key in this.props.garage){
      console.log(this.props.garage[key])
      garageNodes.push(
        <ul>
          <MyComponents.Garage garage={this.props.garage[key]}/>
        </ul>
      );
    }
  return garageNodes;
  }
});

Upvotes: 1

Related Questions