Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
Assign index to array, and onClick pass it based on item's position

I have a searchbar that shows search suggestions from an API using .filter().includes(string).

In short: I need to dynamically assign index to array of search results - everytime it displays a different amount of results

If someone types 'b' it'll show all items starting with B. However, onClick it will only add the first at the top. Because I hard coded it this way. I need to find a way to set an index for each item of the search filter, and then pass it instead of [0] like so [i] (i = index that corresponds to the desireable search from array) to this function thats executed onClick

    const handleAdd = (e) => { // onClick={handleAdd} 
    e.preventDefault();
    setCryptolist(
      [ ... cryptolist , 
        {
      id: filteredCoins[0]['id'], // [i]
      current_price: filteredCoins[0]['current_price'], // [i]
      name: filteredCoins[0]['name'], // [i]
      symbol: filteredCoins[0]['symbol'], // [i]
      image: filteredCoins[0]['image'], // [i]
      price_change_percentage_24h: filteredCoins[0]['price_change_percentage_24h'], // [i]
      }
    ]
  )
}

As you can see, it's hard coded to add the item with index 0 from this array:

(3) [{…}, {…}, {…}]
0: {id: 'bitcoin', symbol: 'btc', name: 'Bitcoin', image: 'https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579', current_price: 28982, …}

1: {id: 'binancecoin', symbol: 'bnb', name: 'BNB', image: 'https://assets.coingecko.com/coins/images/825/large/bnb-icon2_2x.png?1644979850', current_price: 307.58, …}

2: {id: 'binance-usd', symbol: 'busd', name: 'Binance USD', image: 'https://assets.coingecko.com/coins/images/9576/large/BUSD.png?1568947766', current_price: 1.001, …}

length: 3[[Prototype]]: Array(0)

Please let me know if I explained the problem clearly, and how shoould I tackle it.

Lastly here's how I'm filtering the searches:

  const filteredCoins = coins.filter(coin =>
    coin.name.toLowerCase().includes(search.toLowerCase())
  );

I greatly appreciate any help. 🙏

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Not sure if I 100% understand your problem but I think you have an component like this:

const CoinList = () => {
  // some code..
  const filteredCoins = /* ... */;

  const handleAdd = (e) => { /* ... */ };

  return (
    <div>
      {filteredCoins.map(coin => (
        <div key={coin.id} onClick={handleAdd}>{coin.name}</div>
      )}
    <div>
  );
}

You can pass the index, which is the second argument of the function passed to map, to handleAdd as seen here:

const CoinList = () => {
  // some code..
  const filteredCoins = /* ... */;

  const handleAdd = (e, i) => { /* use i here */ };

  return (
    <div>
      {filteredCoins.map((coin, i) => (
        <div key={coin.id} onClick={(e) => handleAdd(e, i)}>{coin.name}</div>
      )}
    <div>
  );
}

This will allow you to use the index i in your handleAdd function as desired.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda