Trying add dynamic rows in HTML table (React). When, the props are passed on to a different compoment for rendering the table I get a warning Warning: Each child in a list should have a unique "key" prop.
But when the table is rendered in the same component. No warnings!!!
I have looked into other solutions one, two, In solution three, the answer says The key needs to go on the outermost returned element. In your specific case, that means changing this:
. Which I am returning from the row component, but the behaivior is different.
This throws warning
<Box>
<form onSubmit={handleSubmit(onSubmit)}>
<table>
<thead>
<tr>
<th scope="col" width="20%">
Item Name
</th>
<th scope="col" width="6%">
Rack
</th>
<th></th>
</tr>
</thead>
<tbody>
{rowsData.map((data, index) => (
<Rows index={index} data={data} handleChange={handleChange} />
))}
</tbody>
</table>
</form>
<IconButton
mt={4}
variant="pill-add-row"
type="button"
icon={<VscAdd />}
onClick={addTableRows}
/>
</Box>
whereas this does not
<Box>
<form onSubmit={handleSubmit(onSubmit)}>
<table>
<thead>
<tr>
<th scope="col" width="20%">
Item Name
</th>
<th scope="col" width="6%">
Rack
</th>
<th></th>
</tr>
</thead>
<tbody>
{rowsData.map((data, index) => (
// <Rows index={index} data={data} handleChange={handleChange} />
<tr key={data.id}>
<td>
{/* <FormControl isInvalid={errors.iname}> */}
<FormControl>
<Input
type="text"
name="iname"
value={data.iname}
{...register("iname")}
onChange={(event) => handleChange(index, event)}
// placeholder={data.id}
/>
</FormControl>
</td>
<td>
{/* <FormControl isInvalid={errors.rackno}> */}
<FormControl>
<Input
type="number"
name="rackno"
width={"240px"}
value={data.rackno}
{...register("rackno")}
onChange={(event) => handleChange(index, event)}
// placeholder={data.id}
/>
</FormControl>
</td>
<td>
<IconButton icon={<VscAdd />} variant="pill" />
</td>
</tr>
))}
</tbody>
</table>
</form>
<IconButton
mt={4}
variant="pill-add-row"
type="button"
icon={<VscAdd />}
onClick={addTableRows}
/>
</Box>
I have used currentTime, nanoid() for data.id