question regarding "key" in js
Ik this might seem a lil dumb but can someone explain to me why we use "key" in js or react as well
10 Replies
use it where? In keyboard events?
i ll send u code pen
{ANIMALS.map((animal) => (
<option key={animal}>{animal}</option>
))}
this part of the code where i am using map to get an array and return react components
what is the purpose of key here
that is 100% a React thing. afaik it lets react identify which option tag is selected
so is key there absolutely necessary because even when i remove "key" it doesn't effect my application at all.
any time you run through a loop, you usually need a unique identifier on the element. I don't really know react though, so I can't say for sure
š¤· no idea, sorry. I thought you meant
event.key
in keyboard event handlersi should've included the react tag in the post as well
thanks for ur time
yes, you must provide unique key to each element. it helps react know which elements are changed when and if you change them (such as check boxes in form, reorder the list, delete one of elements etc...). but even if your list doesn't change you should still provide the key
and I'm not sure if you're using strict mode, but if you do you should get error in console telling you to give each element unique key prop
yes i am using strict mode, and thank u for ur answer.