Home > Blockchain >  React Warning eliminate Warning: Each child in a list should have a unique "key" prop
React Warning eliminate Warning: Each child in a list should have a unique "key" prop

Time:06-24

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>
    </>
  );
}

Edit dank-flower-u0pch0

CodePudding user response:

In your map, you also get access to the index as well. change DEVICE_ARRAY.map((device) => {... to DEVICE_ARRAY.map((device, idx) => {... and then you can use a template literal to add the index to make them unique:

li key={`label-${idx 1}`}

  • Related