Home > Back-end >  React, conditional rendering inside map method
React, conditional rendering inside map method

Time:06-27

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

CodePudding user response:

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>
    )
  • Related