Skip to content
Related Articles

Related Articles

How to create an unique id in ReactJS ?

Improve Article
Save Article
Like Article
  • Last Updated : 11 Nov, 2021

In this article, we will see the simple steps to create a unique reference ID in react JS. This has many uses such as giving a user uploaded image a unique name for saving in a database.

Approach: We will be using Uuid V4 in this tutorial. Uuid v4 is a React library or package that creates a universally unique identifier (UUID). It is a 128-bit unique identifier generator. The bits that comprise a UUID v4 are generated randomly and with no inherent logic. Because of this, there is no way to identify information about the source by looking at the UUID, so it is very unique.

Below is the step by step implementation:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2:  After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: After creating, your project directory should look like this.

Project Directory

Step 3: Delete all files from the src folder except for index.js and app.js(not necessary but recommended). Next, install UUID v4 using the following command:

npm install uuidv4

Step 4: Import the package into your component, page or code etc. You can now assign the Unique ID to any variable using the below code. unique_id is an example here, it can be any variable name. We are storing the unique id in it. You can then console.log() it to see the output and also use it wherever needed. Here I am displaying it in a <p> tag.

If the unique id is too long, you can slice it or extract a small part of it to use. We can use the JavaScript slice() function here. It takes 2 parameters, the number of characters and the last character.The variable small_id will store this sliced id. We will output both the ids on the browser to see the difference.

App.js




//import uuid v4
import { v4 as uuid } from 'uuid';
  
export default function App() {
  const unique_id = uuid();
  const small_id = unique_id.slice(0,8)
  return (
    <div className="App">
      <h1>Unique ID</h1>
      <p>{unique_id}</p>
      <h1>Sliced Unique ID</h1>
      <p>{small_id}</p>
    </div>
  );
}

Step to run the application: To run the app, use the following command:

npm start

Output: Now if you run the app, the unique id will be shown below the heading. Each time you refresh, a new and unique id will be shown with no repetition.

Output

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!