I am trying to get the key of an element which i rendered by using map function giving a unique key. Anybody who know can comment the answer.
CodePudding user response:
You can do it this way.
<div>
{items.map((item, index) => <div key={index} onClick={(e) => yourFunction(key)}>something</div>)}
</div>
On click function with key
.
function yourFunction(key) {
const selectedItem = data[key];
// logic here.
}
CodePudding user response:
Keys serve as a hint to React but they don’t get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name.
Example:
const content = posts.map((post) =>
<Post
key={post.id}
id={post.id}
title={post.title} />
);
See React's documentation: https://reactjs.org/docs/lists-and-keys.html#keys-must-only-be-unique-among-siblings
CodePudding user response:
it can be easily done,we just have to pass the key in the function which we want to call on that event.
{item && item.map((i)=> (<h1 key={i.key} onClick={(i)=>findKey(i.key)}>Item {i.value}</h1>))
And our fuction should be like:
function findKey(key){
console.log(key)
}