skip to Main Content

I am learning React and I built this app. While running code, I got this warning on console: Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of ToDos

This is my code:

return (
    <div className='container' style={todoStyle}>

      <h3 className='my-3'>ToDos List</h3>

      {props.todos.length === 0 ?
        "No ToDos to display" :
        props.todos.map((todo) => {
          return (
            <>
              <ToDoItem todo={todo} key={todo.sno} onDelete={props.onDelete} /> <hr />
            </>
          )
        })

      }

    </div>
  )

I have added key to ToDoItem yet I am getting this warning.

2

Answers


  1. Chosen as BEST ANSWER

    I did some changes and it worked. I removed hr tag from return statement and returned only ToDoItem and used hr to show horizontal line in ToDoItem.js file. My new code looks like this:

    return (
        <div className='container' style={todoStyle}>
    
          <h3 className='my-3'>ToDos List</h3>
    
          {props.todos.length === 0 ?
            "No ToDos to display" :
            props.todos.map((todo) => {
              return (
                <ToDoItem todo={todo} key={todo.sno} onDelete={props.onDelete} />
              )
            })
    
          }
    
        </div>
      )
    

    ToDoItem.js:

    return (
        <>
          <div>
            {/* <h4>{todo.sno}</h4> */}
            <h4>{todo.title}</h4>
            <p>{todo.description}</p>
            <button className="btn btn-sm btn-danger" onClick={() => { onDelete(todo) }}>Delete</button>
          </div>
          <hr />
        </>
    
      )
    

  2. This warning is coming probably because the unique key prop should be on outermost element in the DOM tree.

    return (
            <div className='container' style={todoStyle}>
              <h3 className='my-3'>ToDos List</h3>
              {props.todos.length === 0 ?
                "No ToDos to display" :
                props.todos.map((todo, _i) => {
                  return (
                    <React.Fragment key={`${_i}-${todo.sno}`}>
                      <ToDoItem todo={todo} onDelete={props.onDelete}/> 
                      <hr/>
                    <React.Fragment/>
                  );
                });
              }
            </div>
         )

    Also I’m not sure if todo.sno is unique thus implement index from map function to ensure the key prop remains unique.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search