2

i want to loop in this array, and i don't have key in array

my array

const array = ['name1','name2','name3']

after that the proplem on console is

Warning: Each child in a list should have a unique "key" prop

my component

{
    items.map((item) => {
        return (
          <div className="flex-shrink-0 py-1">
            <button
              key={}
              onClick={() => onFillter(item)}
              type="button"
              className="... tailwind css"
            >
              {item}
            </button>
          </div>
       );
    })
}

i try to added math.random() in key -> bad result added number to array -> bad result

  • 4
    Why not use the item itself as key? `key={item}` – 0stone0 Dec 20 '22 at 17:15
  • 1
    I hope [this post](https://stackoverflow.com/a/39549510/16466946) helps – kikon Dec 20 '22 at 17:19
  • @kikon The accepted answer to that link is a really bad idea using the index of the array, especially if the array gets mutated. – Keith Dec 20 '22 at 17:22
  • Mapping gives you a second argument called `index` which is just a numerical value for the item being mapped. That's what I use for the key. It would look like this: { items.map((item, index) => { return (
    ); }) }
    – Sako Dec 20 '22 at 17:25
  • @Sako It's best avoided, if the array gets mutated your in for funky results. like Ostone0 has pointed out, just pass the Object, objects are unique already.. Job done. – Keith Dec 20 '22 at 17:26
  • @Keith right, I recommend OP to read the full post – kikon Dec 20 '22 at 17:27
  • i am using it but not work – Othman Jabes Dec 20 '22 at 17:34
  • now i using it https://stackoverflow.com/a/68511264/19694485 and work 100% – Othman Jabes Dec 20 '22 at 17:34
  • Did you not read the comments for that link??, and what issue did you have with @0stone0 recommendation?. – Keith Dec 20 '22 at 20:41

0 Answers0