1

I have the following code and I want to apply a conditional rendering, because the index 0 does not exist. I don't want to render the information for this particular index. How can I do it?

return (
        <section>
            {pokemonCards.map((pokemon, index) =>             
                <div key={index}>
                <img 
                    src={`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${index}.png`} 
                    alt={pokemon.name}/>
                <p>{pokemon.name}</p>
                </div>
            )}
            <button 
                className="get-more-button" 
                onClick={getMorePokemons}>Get more pokemons
            </button>
        </section>
    )
3
  • 3
    Why don't you apply a pokemonCards.shift() before using that array ? It will remove the first element. You can read more here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jun 26, 2022 at 17:13
  • Thanks! Where exactly this method would be written in the code? inside the return? Commented Jun 26, 2022 at 17:24
  • 1
    Before the return, so the array is modified when you use it. Commented Jun 27, 2022 at 19:22

2 Answers 2

2

This should work:

return (
        <section>
            {pokemonCards.map((pokemon, index) =>             
                {index === 0 ? null : <div key={index}>
                <img 
                    src={`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${index}.png`} 
                    alt={pokemon.name}/>
                <p>{pokemon.name}</p>
                </div>
            )}
            <button 
                className="get-more-button" 
                onClick={getMorePokemons}>Get more pokemons
            </button>}
        </section>
    )
Sign up to request clarification or add additional context in comments.

Comments

1

You could do as below if you do not want to render an empty div for the nonexisting pokemon:

 return (
    <section>
      {pokemonCards.map(
        (pokemon, index) =>
          index !== 0 && (
            <div key={index}>
              <img
                src={`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${index}.png`}
                alt={pokemon.name}
              />
              <p>{pokemon.name}</p>
            </div>
          )
      )}
      <button className="get-more-button" onClick={getMorePokemons}>
        Get more pokemons
      </button>
    </section>
  );

1 Comment

Should we not to add the index as a key?

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.