I’m getting an error that each child in a list should have a unique "key" prop.
The error only appears on the second .map function.
import React from 'react'
import { Table } from 'react-bootstrap'
const ActivityTable = () => {
const activities = [{ id: 100, name: 'reading' }, { id: 101, name: 'coding' }, { id: 200, name: 'eating' },]
const date = new Date();
const currentDay = date.getDate();
const currentMonth = date.getMonth() + 1;
const currentYear = date.getFullYear();
const getAllDaysInMonth = (month, year) =>
Array.from(
{ length: new Date(year, month, 0).getDate() }, // get next month, zeroth's (previous) day
(_, i) => new Date(year, month - 1, i + 1) // get current month (0 based index)
);
const allDatesInMonth = getAllDaysInMonth(currentMonth, currentYear)
const listOfCurrentDays = allDatesInMonth.map(x => x.toLocaleDateString([], { day: "numeric" }))
//console.log(allDatesInMonth.map(x => x.toLocaleDateString([], { month: "short", day: "numeric" })))
if (currentDay >= 0 || currentDay < 8) {
var listOfCurrentWeekDays = listOfCurrentDays.slice(0, 7)
} else if (currentDay > 7 || currentDay < 15) {
var listOfCurrentWeekDays = listOfCurrentDays.slice(7, 14)
} else if (currentDay > 14 || currentDay < 22) {
var listOfCurrentWeekDays = listOfCurrentDays.slice(14, 21)
} else if (currentDay > 21) {
var listOfCurrentWeekDays = listOfCurrentDays.slice(20, 31)
}
console.log(listOfCurrentWeekDays)
return (
<Table striped>
<thead>
<tr>
<th>#</th>
{
(listOfCurrentWeekDays).map(function (item, key) {
return (
<th key={key}>
{item}
</th>
)
})
}
</tr>
</thead>
<tbody>
{
(activities).map(function (item, key) {
return (
<tr>
<th key={item.id}>
{item.name}
</th>
</tr>
)
})
}
</tbody>
</Table>
)
}
export default ActivityTable
At first, I was using key={key} for both .map functions.
I thought as both key values start with 0,1,2… that that was the reason why I was getting this error.
I have added the id property to the activities array so that both .map functions have different keys.
But I’m still getting this error.
4
Answers
The problem is that you are using
key
in theth
; however, you are expected to add it totr
, since it is the highest tag in the list item.In your second
.map
example, you’re applying the key to a nested component, not the root — as with the first example, you’re applying the key to the root of the mapped component. It should be noted that the key is only relevant within the parent component. Applying the key to the roottr
tag of the mapped component should do the trick.You are getting this error because you are giving the key property to the
<th>
tag instead of<tr>
tag.In order to solve this problem, use the code below:
You just put the key in the wrong place.
It needs to be on the parent element.
Side note: Try to avoid using var, stick with let and const.
I hope it will help you. 🙂