React Warning eliminate Warning: Each child in a list should have a unique "key" prop.
I would like to eliminate the 「Warning: Each child in a list should have a unique "key" prop.」
The code is as follows
import { useState } from "react";
const SIZE_ARRAY = [
{
label: "Small",
value: "sm"
},
{
label: "Medium",
value: "md"
},
{
label: "Large",
value: "lg"
}
];
const DEVICE_ARRAY = [
{
deviceLabel: "PC",
deviceValue: "pc"
},
{
deviceLabel: "Tablet",
deviceValue: "tablet"
},
{
deviceLabel: "Mobile",
deviceValue: "mobile"
}
];
export default function SampleLoop() {
const [option, setOption] = useState();
return (
<>
<ul>
{SIZE_ARRAY.map((size) => {
const { label, value } = size;
return (
<li key={label}>
<span>Margin : {label}</span>
{DEVICE_ARRAY.map((device) => {
const { deviceLabel, deviceValue } = device;
return (
<>
<input
key={deviceLabel}
onChange={(newValue) => {
setOption({
...option,
margin_size: {
...option.margin_size,
[value]: {
...option.margin_size[value],
[deviceValue]: newValue
}
}
});
}}
/>
</>
);
})}
</li>
);
})}
</ul>
</>
);
}
It is a nested form of two loops.
Is there a different position to attach the KEY?
In here:
{DEVICE_ARRAY.map((device) => {
const { deviceLabel, deviceValue } = device;
return (
<>
<input
key={deviceLabel}
onChange={(newValue) => {
setOption({
...option,
margin_size: {
...option.margin_size,
[value]: {
...option.margin_size[value],
[deviceValue]: newValue
}
}
});
}}
/>
</>
);
})}
The "root element" of each child is the </>
, ie <Fragment/>
, not <input/>
. So you should define the key in the former instead. Although quite frankly, you don't need that Fragment
here unless you omitted some components in your posted code.
BTW, you can't use the fragment shorthand if you specify any props in it. ie this doesn't work:
< key={deviceLabel}>
</>
Instead, do this
<Fragment key={deviceLabel}>
</Fragment>
Remove the redundant fragment around <input>
import { useState } from "react";
const SIZE_ARRAY = [
{
label: "Small",
value: "sm"
},
{
label: "Medium",
value: "md"
},
{
label: "Large",
value: "lg"
}
];
const DEVICE_ARRAY = [
{
deviceLabel: "PC",
deviceValue: "pc"
},
{
deviceLabel: "Tablet",
deviceValue: "tablet"
},
{
deviceLabel: "Mobile",
deviceValue: "mobile"
}
];
export default function SampleLoop() {
const [option, setOption] = useState();
return (
<ul>
{SIZE_ARRAY.map((size) => {
const { label, value } = size;
return (
<li key={label}>
<span>Margin : {label}</span>
{DEVICE_ARRAY.map((device) => {
const { deviceLabel, deviceValue } = device;
return (
<input
key={deviceLabel}
onChange={(newValue) => {
setOption({
...option,
margin_size: {
...option.margin_size,
[value]: {
...option.margin_size[value],
[deviceValue]: newValue
}
}
});
}}
/>
);
})}
</li>
);
})}
</ul>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.