ReactHustle

How to Generate Random and Unique Keys or IDs in React

Jasser Mark Arioste

Jasser Mark Arioste

How to Generate Random and Unique Keys or IDs in React

Hello, hustlers! In this tutorial, you'll learn how to generate random and unique keys or ids.

Introduction #

Sometimes, you need to create random keys or ids in React. There are a couple of use cases why we need to generate ids:

  1. Re-render / Reset a component by resetting the key prop.
  2. Generate keys when iterating a list or array.
  3. Generate a unique ID for database objects. 

By the end of this tutorial, we'll learn how to generate IDs for these different use cases. 

Resetting a Component by using the key prop #

In React, you can force re-render a component by using the key prop. Remember that when a component's prop changes, it triggers a re-render. Consider the following code:

import React, { useState } from "react";

const ComponentA = () => {
  const date = new Date();
  return <div>This componenent was rendered on {date.toISOString()}</div>;
};

// Generate ID using nanoid
const ContainerComponent = () => {
  const [id, setId] = useState(0);
  return (
    <div className="p-2">
      <ComponentA key={id} />
      <div>
        <button
          className="p-2 bg-indigo-500 text-white"
          onClick={() => {
            const date = new Date();
            setId(date.getTime());
          }}
        >
          Re-render Component
        </button>
      </div>
    </div>
  );
};

export default ContainerComponent;
1234567891011121314151617181920212223242526272829

In this scenario, we don't have to use a unique or random ID, we just use the Date.getTime method to re-render the component.

Here's the output:

React rerender a component by changing the key prop.

Generating Random Keys for Lists or Arrays #

If you want to render an array and want to use random ids, we can use nanoid package. The nanoid package is a small (<1kb), open-source, unique id generator for javascript.  It's a very useful package that can handle most use cases.

First, let,s install it using the following command:

yarn add nanoid

Here's how you would use it:

import React from "react";

const Example2 = () => {
  const items = new Array().fill("x");
  return (
    <div>
      {items.map((item) => {
        return <div key={nanoid()}>{item}</div>;
      })}
    </div>
  );
};

export default Example2;
1234567891011121314

Generating a Unique ID for Database Objects #

If you need to generate a unique id for database objects, we can still use the nanoid package. Normally, you generate the ids in the backend but some APIs need the id on the front-end, here's an example of generating an id when creating an account:

import { nanoid } from "nanoid";
import React from "react";

const Example3 = () => {
  return (
    <div>
      <h1>Sign Up </h1>
      <form
        onSubmit={(e) => {
          e.preventDefault();
          fetch("/api/signup", {
            body: JSON.stringify({
              id: nanoid(),
              //@ts-ignore
              email: e.target.email.value,
              //@ts-ignore
              password: e.target.password.value,
            }),
            method: "POSt",
          });
        }}
      >
        <input name="email" type="email" placeholder="Email"></input>
        <input name="password" type="password" placeholder="Password"></input>
        <button>Create Account</button>
      </form>
    </div>
  );
};

export default Example3;
12345678910111213141516171819202122232425262728293031

Here's the output when the form is submitted:

Generate random/unique id in React

Conclusion #

You learned how to generate random and unique ids for different scenarios in React.

If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter or follow me on GitHub.

Resources #

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle