Categories
React Answers

How to get the key prop from a React element?

Spread the love

Sometimes, we want to get the key prop from a React element.

In this article, we’ll look at how to get the key prop from a React element.

How to get the key prop from a React element?

To get the key prop from a React element, we can store it in a custom attribute.

For instance, we write

const onClick = (event) => {
  console.log(event.target.getAttribute("data-key"));
};

<button data-key={1} onClick={onClick}>
  Press Me
</button>

to set the data-key attribute to 1.

Then we set the onClick prop to the onClick function.

In it, we get the data-key attribute’s value with event.target.getAttribute("data-key").

event.target is the button we clicked on.

Conclusion

To get the key prop from a React element, we can store it in a custom attribute.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *