Ao renderizar uma lista dinâmica no React ou React Native, recebo o seguinte aviso:
Warning: Each child in a list should have a unique "key" prop.
Apesar disso, as coisas parecem funcionar bem sem a prop key
. Veja este exemplo:
function shuffleArray(array) {
var currentIndex = array.length,
randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex],
array[currentIndex]
];
}
return array;
}
function App() {
const [pokemons, setPokemons] = React.useState([
{
name: "Bulbasaur",
img: "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/001.png"
},
{
name: "Ivysaur",
img: "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/002.png"
},
{
name: "Venusaur",
img: "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/003.png"
},
{
name: "Charmander",
img: "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/004.png"
},
{
name: "Charmeleon",
img: "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/005.png"
},
{
name: "Charizard",
img: "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/006.png"
},
{
name: "Squirtle",
img: "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/007.png"
},
{
name: "Wartortle",
img: "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/008.png"
},
{
name: "Blastoise",
img: "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/009.png"
}
]);
function shuffle() {
setPokemons(shuffleArray([...pokemons]));
}
return (
<ul>
<button onClick={shuffle}>Embaralhar</button>
{pokemons.map((pokemon) => (
<li onClick={() => console.log(pokemon.name)}>
<img src={pokemon.img} alt={pokemon.name} />
<span>{pokemon.name}</span>
</li>
))}
</ul>
);
}
ReactDOM.render(<App /> , document.querySelector("#app"));
ul {
padding-right: 2rem;
padding-left: 2rem;
}
li {
list-style: none;
display: flex;
align-items: center;
padding: 10px;
border: 2px solid #ccc;
}
li:hover {
background-color: #deebff;
cursor: pointer;
}
img {
height: 40px;
width: 40px;
}
span {
font-size: 20px;
}
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="app"></div>
Para resolver esse aviso, já encontrei várias respostas aqui utilizando o índice como key
, então tenho as seguintes dúvidas:
Para que serve essa propriedade
key
?Eu preciso definir uma
key
somente ao percorrer um array?Como posso definir uma chave? Posso utilizar o índice, um número aleatório ou tem outro jeito melhor?