Posts > generate keys for your list item ( react )

generate keys for your list item ( react )

I usually just use an index for my key values when creating a list of items in React, and for me, that will do. This will solve my issue with need a key for your list items (not the actual warning) warning message in my console when building React applications.

arrays.map((item, index) => (
	<li key={index}>
		<p>{item}</p>
	</li>
))

I found out about this recently as a great way to generate a key id on your list of items. crypto.randomUUID() generates a unique key for you.

We’ll need to generate them dynamically when we get our list item. So more code 😅

// for eaxample we have a list of items we need to display for example tags

export default function Tags({tags}){
	//1. add our data to useState
	const [useTags, setTags] = useState(null)

	//2. create a useEffect function that when data is available create a id for them
  useEffect(() => {
    const techWithId = tags.map((item) => {
      return {
        name: item,
        id: crypto.randomUUID(),
      };
    });
    return setTags(techWithId);
  }, [tags]);

	return(
		<ul>
			{
				//3. then display your new data with id
				useTags &&
	        ueTags.map((item) => <li key={item.id}>{item.name}</li>)}
			}
		</ul>
	)
}