Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
What to use as key when rendering a list of elements in react if the objects have no property which can be used as an unique identifier?

Lets say I'm building a to do list and I built the toDos like this:

    const toDo = {
        title: title,
        finished: false,
    }

before pushing them to the array that contains all toDos. Once I want to map over them and return JSX, I need to supply them with a unique key, but in this case, I don't have a key on the object, so what do I need to supply in this case?

const mappedToDoList = toDoList?.map((element) => {
    return (
        <div className='to-do' key={???}>
            <p>{element.title}</p>
        </div>
    )
})

I can't use the index because it causes problems as soon as I start adding/removing toDos.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

you have two options here:

  1. the suggested way is to generate a unique key when adding a new todo like this:
const toDo = {
  id: new Date().getTime(), //a better way might be to use a uuid library to generate this
  title: title,
  finished: false,
};
  1. is to use index + title as key just to make react happy, like this:
const mappedToDoList = toDoList?.map((element, index) => {
    return (
        <div className='to-do' key={element.title + index}>
            <p>{element.title}</p>
        </div>
    )
})
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use uuid library

npm install uuid

Then you can add a unique id for your item

  
import { v4 as uuidv4 } from 'uuid';
 const toDo = {
        id: uuidv4(),
        title: title,
        finished: false,
    }

about 4 years ago · Juan Pablo Isaza Relatório

0

You can map over the list like this:

const numbers = [1, 2, 3, 4, 5];

const listItems = numbers.map((number) =>
  <li>{number}</li>
 );
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda