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
Jochem
Jochemā€¢10mo ago
use it where? In keyboard events?
theboyduddus
theboyduddusOPā€¢10mo ago
i ll send u code pen
theboyduddus
theboyduddusOPā€¢10mo ago
{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
Jochem
Jochemā€¢10mo ago
that is 100% a React thing. afaik it lets react identify which option tag is selected
theboyduddus
theboyduddusOPā€¢10mo ago
so is key there absolutely necessary because even when i remove "key" it doesn't effect my application at all.
Jochem
Jochemā€¢10mo ago
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 handlers
theboyduddus
theboyduddusOPā€¢10mo ago
i should've included the react tag in the post as well thanks for ur time
Tenkes
Tenkesā€¢10mo ago
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
theboyduddus
theboyduddusOPā€¢10mo ago
yes i am using strict mode, and thank u for ur answer.
Want results from more Discord servers?
Add your server