If you clicked on this article thinking it has something to do with crypto currency, I'll let you off easy and quickly say that it most certainly has nothing to do with that kind of crypto. But if you've ever found yourself in a pinch needing a unique ID when none exists, then you're at the right place!
Today's post is going to be short and sweet, with a little bit of context surrounding that sweetness.
As developers, we're constantly iterating over items and needing to generate unique IDs or keys for each of those items. Sometimes we're able to retrieve it pretty easily, based on what's in the returned API call. Other times, we're needing to hack together our own helper function or GASP
USE THE INDEX AS THE KEY
Which actually does work in some cases, but not all. But that forbidden practice isn't what I'm here to talk about. What I'm here to talk about is a handy-dandy method you can use that's widely supported across all major browsers, AND you don't even need to import it or list it in your dependencies file! So without further ado, let's see it in action:
const resultFromApiCall = [...data];
{resultFromApiCall.map(item => (
<YourComponent key={crypto.randomUUID()}/>
))}
That's pretty much all there is to it. Simply plug that into your key or anything else that will need its own unique ID and it will safely generate that for you. The returned ID will be a string that looks something like this:
"e75b6774-580c-41f1-8c70-bb6a8be40591"
The ID that's generated is currently a version 4 UUID, which basically means that for each section of that ID separated by hyphens, it uses cryptographically secure byte generation using hexadecimal encoding. The very same hexadecimal system that we use when choosing colors in CSS, 0-9 and a-f!
If you'd like to read more about this process, check out this link.
It's also important to note that this method is only functional within secure contexts, so don't use it on your project if it uses the dated http://
protocol, only https://
.
That's all for this one, thank you as always and I'll catch you in the next one!
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.