wail
wail

Reputation: 65

how to add unique key using uuid in react js?

I read a comment from someone here in StockOverflow who talks about React keys and said that

'React expects STABLE keys, meaning you should assign the keys once and every item on your list should receive the same key every time, that way React can optimize around your data changes when it is reconciling the virtual DOM and decides which components need to re-render. So, if you are using UUID you need to do it at the data level, not at the UI level',

and I want to ask if anyone know how to apply this in a real code where we have for example a context component that have an array of objects and another component that maps through this array, how can we apply this using uuid() or any other package.

Upvotes: 1

Views: 7564

Answers (2)

Mahfod
Mahfod

Reputation: 315

You can install react-uuid

import React from 'react'
import uuid from 'react-uuid'

const array = ['one', 'two', 'three']

export const LineItem = item => <li key={uuid()}>{item}</li>

export const List = () => array.map(item => <LineItem item={item} />)

Or you can use crypto.randomUUID() directly without packages.

Upvotes: 1

Mario Petrovic
Mario Petrovic

Reputation: 8332

Although it is not a common requirement for you to generate id on FE, it happens some times, so using uuid is a really good way of doing that. It is easy and implementation is quick.

I made an example for you here how to do it:

import { useEffect, useState } from "react";
import { v1 } from "uuid";
import "./styles.css";

const items: { name: string; id?: string }[] = [
  {
    name: "Name1"
  },
  {
    name: "Name2"
  },
  {
    name: "Name3"
  },
  {
    name: "Name4"
  },
  {
    name: "Name5"
  },
  {
    name: "Name6"
  }
];

export default function App() {
  const [itemList, setItemList] = useState<{ name: string; id?: string }[]>([]);

  useEffect(() => {
    setItemList(items.map((item) => ({ ...item, id: v1() })));
  }, []);

  return (
    <div className="App">
      {itemList.map((item) => (
        <div key={item.id}>
          {item.name} - {item.id}
        </div>
      ))}
    </div>
  );
}

In this example your array is empty at the beginning and after first useEffect gets populated by items with uuid generated ids:

And code sandbox code

Upvotes: 2

Related Questions