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.
you have two options here:
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,
};
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>
)
})
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,
}
You can map over the list like this:
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li>{number}</li>
);