Search code examples
javascriptreactjsmap-function

How can create uniqe value in map function? Its need for key value


I am trying to learn JS right now. And started to make a little learning and example project.

I got an issue right now. I am studying on react route system. So I have to send a unique value to create a unique path for my pokemons (I use pokeAPI ) but this API does not give a unique value for pokemons just gives names and URLs. A got a 20 pokemons on my Pokemon Listing page.

Now I need to unique id to send PokemonShowComponent. How can I find a unique id for this purpose?

    return (
    <div>
      <h1> Pokemon pages </h1>
      <div>
        {pokemons.map((pokemon, id) => (
          <h3 key={id}>
            <Link to={"/pokemon/${id}"}> {pokemon.name} </Link>
          </h3>
        ))}
      </div>
    </div>
  );

I want an id parameter count like a forEach method and return 1 to 20 every step. Like an i++.

It can be possible?


NOTE: Pokemon variable comes this lines of code.

const fetchPokemons = async () => {
    const data = await fetch("https://pokeapi.co/api/v2/pokemon/");

    const pokemons = await data.json();
    console.log(pokemons.results);
    setPokemons(pokemons.results);
  };

Solution

  • {pokemons.map((pokemon, id) => (
        <h3 key={id}>
            <Link to={"/pokemon/${id}"}> {pokemon.name} </Link>
           </h3>
       ))}
    

    your second parametr id should work

    But I think you will need to do {`/pokemon/${id}`} instead of quotes