Object ID Control: UUID

By Yeo Yong Kiat in ReactJS

5 min read
Worried about how to track your object IDs? Don't worry, in the world of coding, there's a library for everything. Today, we look at how to use the UUID package for effective object ID control in React.

UUID, Not Another Thingamajig Again!

Singaporeans aren't the only ones adept at acronymisation, coders do it all the time too! UUID stands for Univeral Unique Identifier, and it's a JS package to help you keep track of all those pesky object IDs you now have to pass on as attributes in React.

Installation

Go to your terminal and key in the following command to install UUID:

npm install uuid

Usage

Let's return to your App.js component (or wherever you're using object IDs) and import this package. Then, replace any hardcoded object ID with "uuidv4()":

import React from 'react';
// Import uuid here
import {v4 as uuidv4} from 'uuid';

// Use uuidv4() here to generate the ids
const data = {
    title: "Best App",
    contents: "That's right baby!",
    bulletItems: [
                  {name: "Item 1",
                   id: uuidv4()},
                  {name: "Item 2",
                   id: uuidv4()},
                  {name: "Item 3",
                   id: uuidv4()}
                  ]
};

function App() {
    return (
      

{data.title}

{data.contents}

    {data.bulletItems.map( (item) => { return (
  • {item.name}
  • ) })}
); }; export default App;

And that's it, you no longer have to worry about generating or keeping track of your object IDs. Each and every object ID will be generated by UUID, and they will be unique. You're on your way to focus more on coding and less on code upkeep. :)

In the next post, we see how to generate the first of many "child" components to App.js.

Find more ReactJS stories on my blog. Have a suggestion? Contact me at [email protected].