Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

238
Vistas
Create list in reactjs from nested arrays

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%27s_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?
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

import React from "react";
import { render } from "react-dom";
import axios from "axios";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      result: [],
      query: ""
    };
    this.handleChange = this.handleChange.bind(this);
    this.fetchingData = this.fetchingData.bind(this);
  }

  handleChange(e) {
    this.setState({ query: e.target.value });
  }

  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 }));
    }
  }

  componentDidMount() {
    this.fetchingData();
    setTimeout(() => {}, 200);
  }

  render() {
    const key = this.state.result[1]; // name
    const value = this.state.result[3]; // link

    const mergedResults = key && key.map(function (x, i) {
      return { result: x, link: value[i] };
    })

    return (
      <div id="main">
        <input
          id="input"
          placeholder="search"
          value={this.state.query}
          onChange={this.handleChange}
        ></input>
        <button id="search" onClick={this.fetchingData}>
          Search
        </button>
        <div>
          <ul>
            {mergedResults && mergedResults.map((item, i) => (
              <li key={i}>
                <a href={item.link}>{item.result}</a>
              </li>
            ))}
          </ul>
        </div>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

here is my solution, live working example here https://codesandbox.io/s/react-basic-class-component-forked-s0qoe

code explanation - I just map result arrays 1 and 3 here

 const key = this.state.result[1]; // name
 const value = this.state.result[3]; // link

 const mergedResults = key && key.map(function (x, i) {
    return { result: x, link: value[i] };
 })

then map it

<ul>
   {mergedResults && mergedResults.map((item, i) => (
     <li key={i}>
        <a href={item.link}>{item.result}</a>
     </li>
    ))}
</ul>
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda