0

I receive data from an open api which is stored in an array in state. Then I mapped the array to output it in list items and gave them keys additionally. (this is working so far)

  1. I want to display the position of every element in the array in another list items. (this is not working). (The result should be 1-17 of course).
  2. Then I want to compare every elements position to a given position. So, if ItemPosition[5] = 6 do...
import React, { Component } from 'react';
import axios from 'axios';
import './App.css';


class App extends Component {

  state = {
    teams: []
  }

  componentDidMount() {
    axios.get(`https://www.openligadb.de/api/getbltable/bl1/2019`)
      .then(res => {
        const teams = res.data;
        this.setState({ teams });
      })
  }

  render() {
    return(
    <ul>
      {this.state.teams.map(p => <li key={p.id}>{p.TeamName}</li>)}
      // next line is not correct
      {this.state.teams.map(t => <li key={t.id}>{t.key}</li>)}
    </ul>
  );
  }
}


export default App;

1 Answer 1

1

You can access the index of the array as the second parameter of map like this:

{this.state.teams.map((t, index) => <li key={t.id}>{index}</li>)}

And you can use this index, to compare the items.

Hope this helps.

Sign up to request clarification or add additional context in comments.

8 Comments

Sure, did it now!
Sry, here it is :) : onClickButton = () => { if (this.state.teams[7].TeamName === "FC Bayern") { this.setState((prevState) => ({ gram: prevState.gram + 1 })); } else { this.setState((prevState) => ({ gram: prevState.gram - (1 - this.state.teams.TeamName.findIndex(teamName => teamName.value === "FC Bayern")) })); } };
I want to test if a Teamname is at a special position in an array (working). If not I want to get the difference between a given number (in this case 1) and the position of the Teamname which i compared and update it to the state. A negativ result is okay and appreciated.
Can you show some data, how you save it and what your structure looks like ?
I did a fiddle for you of my component. Is this enough for you and can you see it? jsfiddle.net/Van_Gram/n5q8dx2s
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.