React Error: Each child in a list should have a unique "key" prop

Viewed 126

I am a beginner at React. I wrote this code and got an Error

import { DoItem } from '../MyComponents/DoItem'
export const ToDo = (props) => {
    return (
        <div className="container">
            <h3 className="text-center">To Do List</h3>
            {props.todos.map((todo) => { 
                return ( 
                    <>
                        <DoItem const todo={todo} onDelete = {props.onDelete} /> 
                        <hr />
                    </>
                    ) 
            })}
        </div>
    )
}

Here's the error Each child in a list should have a unique "key" prop.

I looked online and found that I have to use a key. I inserted the key
<DoItem const todo={todo} key={todo.nos} onDelete = {props.onDelete} />

But the error still didn't go after I reload the page.

3 Answers
import { DoItem } from '../MyComponents/DoItem'
export const ToDo = (props) => {
    return (
        <div className="container">
            <h3 className="text-center">To Do List</h3>
            {props.todos.map((todo, i) => { 
                return ( 
                    <key={i}>
                        <DoItem const todo={todo} onDelete = {props.onDelete} /> 
                        <hr />
                    </>
                    ) 
            })}
        </div>
    )
}

Please add a unique key to every item

{props.todos.map((todo, index) => { 
                return ( 
                    <div key={index}>
                        <DoItem const todo={todo} onDelete = {props.onDelete} /> 
                        <hr />
                    </div>
                    ) 
            })}

Please have a try and let me know if it works or not.

Yeah, you should add a key prop to anytime you're rendering an Array.


import { DoItem } from '../MyComponents/DoItem'
export const ToDo = (props) => {
    return (
        <div className="container">
            <h3 className="text-center">To Do List</h3>
            {props.todos.map((todo,index) => { 
                return ( 
                    <div key={index | the id of the todo}>
                        <DoItem const todo={todo} onDelete = {props.onDelete} /> 
                        <hr />
                    </div>
                    ) 
            })}
        </div>
    )
}

Related