Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React keys for an array of strings

I have a question. How can I generate key for array of string? It is not object, in object I could put id and it would solve the problem. So what should I do in just array? Indexes as key is not a good practice so I am stuck.

const ingredients = ['rice', 'curry', 'chicken]



    {props.ingredients.map((ingredient) => (
                <Box>{ingredient}</Box>
          ))}
like image 813
Kay Avatar asked Jun 05 '26 09:06

Kay


2 Answers

If you don't have any duplicate ingredients, using the ingredient name as the key would be fine.

{props.ingredients.map((ingredient) => (
    <Box key={ingredient}>{ingredient}</Box>
))}

If you will have duplicate ingredients, and you really care about getting the key right, you could use the index if the index won't change:

{props.ingredients.map((ingredient, i) => (
    <Box key={i}>{ingredient}</Box>
))}

(Using the index isn't universal bad practice, it's just only suitable for some situations)

If you could have duplicate ingredients and the index can change, and you really want to fix this, change it to an array of objects instead of an array of strings, with a uniquely identifying attribute on each object that you can use as a key.

like image 60
CertainPerformance Avatar answered Jun 07 '26 23:06

CertainPerformance


const ingredients = ['rice', 'curry', 'chicken']
 
{props.ingredients.map((ingredient, index) => ( 
   <Box key={index}>{ingredient}</Box>
 ))}
like image 42
Vida Hedayati Avatar answered Jun 07 '26 23:06

Vida Hedayati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!