iripoli
iripoli

Reputation: 35

Accessing an element inside an array with multiple objects

I'm trying to use an api with football teams, I want to simply render the name of the teams in a div or a list. But it just render the last one.

When I console.log it, it shows all the teams

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      teams: [],
      isLoaded: false
    }
  }
  componentDidMount() {
    fetch('https://www.thesportsdb.com/api/v1/json/1/search_all_teams.php?l=English%20Premier%20League')
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          data: json,
        })
      })
  }
  render() {
    var {
      isLoaded,
      data
    } = this.state;
    if (!isLoaded) {
      return <div> Loading... < /div>
    } else {
      for (var key in data.teams) {
        if (data.teams.hasOwnProperty(key))
          console.log(data.teams[key].strTeam)
      }
      return ( <div className = "App" >
        Premier League Teams!{
          data.teams[key].strTeam
        } </div>
      );
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Upvotes: 1

Views: 63

Answers (2)

Mujibur Rehman Ansari
Mujibur Rehman Ansari

Reputation: 663

Try this,

import React from "react";

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      teams: [],
      isLoaded: false
    };
  }

  componentDidMount() {
    fetch(
      "https://www.thesportsdb.com/api/v1/json/1/search_all_teams.php?l=English%20Premier%20League"
    )
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          data: json
        });
      });
  }

  render() {
    var { isLoaded, data } = this.state;

    if (!isLoaded) {
      return <div>Loading... </div>;
    } else {
      return (
        <div className="App">
          Premier League Teams!
          {data.teams.map(team => (
            <div> {team.strTeam} </div>
          ))}
        </div>
      );
    }
  }
}
export default Test;

Upvotes: 1

matthiasgiger
matthiasgiger

Reputation: 1256

Try this:

return (
    <div className="App">
        Premier League Teams!{data.teams.map(team => team.strTeam)}
    </div>
);

This will loop through the teams array with map and render each one.

Upvotes: 2

Related Questions