How to create an unique id in ReactJS ?
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:
Project Structure: After creating, your project directory should look like this.
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.
Step to run the application: To run the app, use the following command:
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.