Search code examples
javascriptreactjslodash

Generate a unique key for React while using LodashFP


I am trying to use Lodash's map method to render a list of components in React, but the key that is generated is consistently the same because of the way it's returned. Is there any sort of work around for this?

{map((item) => (<Item {...item} key={item.id} />), items}

Solution

  • You should not use index number as a key. here is the blog why?

    The best way I found is this btoa(Math.random()).substring(0, 12) btoa is natively supported in JS.

       console.log(btoa(Math.random()).substring(0, 12))

    key={btoa(Math.random()).substring(0, 12)}