Warning: Each child in a list should have a unique "key" prop. --- thats the message return from console in my react app.
I don't understand why it returns this error when this is my code:
const Usuario = () => {
const [users, setUsers] = useState([])
useEffect(() => {
api.get('/usuario').then((res) => { setUsers(res.data) })
}, [])
//console.log(users[0].perfil[0].departamento)
return (
<>
<Header titulo={"Usuários"} />
<Menu />
<section>
{users.map((user) => (
<div key={user.idUsuario}>
<h3>{user.idUsuario} {user.nomeUsuario}</h3>
<p>E-mail:{user.emailUsuario}</p>
{user.perfil.map(perfis => (
<>
<div key={perfis.idPerfil}>
<p>Perfil: {perfis.nomePerfil}</p>
</div>
{perfis.departamento.map(dep => (
<div key={dep.idDepartamento}>
<p>Departamento: {dep.nomeDepartamento}</p>
</div>
)
)}
</>
)
)}
</div>
)
)}
</section>
</>
)
}
export default Usuario;
I'm following the react documentation (https://reactjs.org/docs/lists-and-keys.html#keys) , but I still keep taking that "Warning"
where am i making mistakes?
CodePudding user response:
This map:
{user.perfil.map(perfis => (
Has no key
on its top-level child:
<>
...
</>
The element immediately under the top-level does, but that React Fragment element does not.
I don't think the short syntax for fragment elements supports attributes, but the longer explicit syntax does:
<React.Fragment key={perfis.idPerfil}>
...
</React.Fragment>
CodePudding user response:
You don't have a key here:
{user.perfil.map(perfis => (
<> /* ... */ </>
)}
Add a key
{user.perfil.map(perfis => (
<React.Fragment key={perfis.id}> /* ... */ </React.Fragment>
)}