Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use npm uuid in reactjs

I have a place wherein I am required to use npm uuid package for generating unique Id's. After installing uuid package, the usage is as follows:

const uuid = require('uuid/v1'); uuid(); 

But I have error which says:

[eslint] Unexpected require(). (global-require) 

My function is as below:

someFunction = (i, event) => {    if(someCondition) {        //generate some unique id        const uuid1 = require('uuid/v1');        uuid1();        //call some function and pass this id        someFunction2(uuid1);     } else{        //generate some unique id        const uuid2 = require('uuid/v1');        uuid2();        //call some function and pass this id        someFunction2(uuid2);     } 

What is the best way to use require in ReactJs.

like image 654
Michael Philips Avatar asked Oct 17 '18 09:10

Michael Philips


People also ask

Why we use UUID in react JS?

js. Using UUIDs can help in securing the information provided and also keeps an unique identifier for each of the information's provided. The unique values helps in easy access of the required data in the databases.

What is NPM UUID?

The uuid, or universally unique identifier, npm package is a secure way to generate cryptographically strong unique identifiers with Node. js that doesn't require a large amount of code.

What is uuidv4?

A Version 4 UUID is a universally unique identifier that is generated using random numbers. The Version 4 UUIDs produced by this site were generated using a secure random number generator.


2 Answers

Try this:

import React from "react"; import ReactDOM from "react-dom"; import uuid from "uuid";  function App() {   return (     <div className="App">       <h1>{uuid.v4()}</h1>     </div>   ); }  const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement); 

This is a working example: https://codesandbox.io/s/0pr5vz48kv

like image 170
You Nguyen Avatar answered Sep 26 '22 06:09

You Nguyen


As of September,2020 I got this working by first, installing the types as

yarn add @types/uuid

then as

import React from "react"; import ReactDOM from "react-dom"; import { v4 as uuidv4 } from 'uuid';  function App() {   return (     <div className="App">       <h1>{uuidv4()}</h1>     </div>   ); }  const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);  

If this code don't work in future, refer to this section of official docs.

like image 23
DevLoverUmar Avatar answered Sep 26 '22 06:09

DevLoverUmar