Home > database >  Create list in reactjs from nested arrays
Create list in reactjs from nested arrays

Time:10-01

I am trying to make a list of results from the Wikipedia API but I can only render the first element from the array.

here is a response example and my code :

["dog",["Dog","Dog meat","Dogecoin","Dogs in warfare","Dog breed","Dog training","Dog tag","Doggystyle","Doge's Palace","Dog Day Afternoon"],["","","","","","","","","",""],["https://en.wikipedia.org/wiki/Dog","https://en.wikipedia.org/wiki/Dog_meat","https://en.wikipedia.org/wiki/Dogecoin","https://en.wikipedia.org/wiki/Dogs_in_warfare","https://en.wikipedia.org/wiki/Dog_breed","https://en.wikipedia.org/wiki/Dog_training","https://en.wikipedia.org/wiki/Dog_tag","https://en.wikipedia.org/wiki/Doggystyle","https://en.wikipedia.org/wiki/Doge's_Palace","https://en.wikipedia.org/wiki/Dog_Day_Afternoon"]]

fetchingData() {
    if (this.state.query === ''){
      this.setState({result: []})
    } else {
    const url = 'https://en.wikipedia.org/w/api.php?action=opensearch&origin=*&search='   this.state.query;
    axios.get(url)
    .then(res => 
          this.setState({result: [res.data]}))
    }
  }

<div>
    {this.state.result.map(function(item, index){
      return(
        <ul>
          <li><a href={item[3][index]} target="_blank" key={index}>{item[1][index]}</a></li>
          </ul>
      )
    })}
      </div>

Any idea on how I can show a list of all the results?

CodePudding user response:

Dont wrap your res.data inside an array. Just make it {result: res.data}

CodePudding user response:

You can map like this your array,

 <ul>
    {data[1].map((item, index) => (
      <li>
        <a href={item} target="_blank" key={index}>
          {item}
        </a>
      </li>
    ))}
  </ul>

I guess you need map inside map , loop inside a loop to achieve this

  • Related