34

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.

Maven Carvalho
  • 319
  • 1
  • 5
  • 14
Uzair Khan
  • 2,812
  • 7
  • 30
  • 48
  • Why do you use conditional imports at all? Also keep in mind that both modules (actually you have the same module in both branches but I assume it was a typo) will be bundled if the condition is not statically computable. – Yury Tarabanko Oct 17 '18 at 09:57
  • Can you give an example? – Uzair Khan Oct 17 '18 at 10:00
  • 1
    Example of what? :) Of conditional import? Well your code is a perfect one. You do `if(a){ require('')} else {require('')}`. The question was why have you written the code this way? Why can't you just do `import uuid1 from 'uuid/v1'` at the top of your file? – Yury Tarabanko Oct 17 '18 at 10:03

12 Answers12

57

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

You Nguyen
  • 9,961
  • 4
  • 26
  • 52
19

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.

DevLoverUmar
  • 11,809
  • 11
  • 68
  • 98
3

You don't have to require the package always. Just require it only once and use it wherever you want.

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

if (condition) {
    some_id = uuidv1();
    some_function(some_id);

} else {
    other_id = uuidv1();
    other_function(other_id);
}

It's as simple as that.

Aravind
  • 534
  • 1
  • 6
  • 18
  • Modified my function as like this: functionName = () => { const uuid = require('uuid/v1'); if(){ const uid = uuid();} }} , It still gives me [eslint] Unexpected require(). (global-require). how to resolve that? – Uzair Khan Oct 17 '18 at 10:04
  • 2
    Do a global import. Not inside functions. Try if that works. – Aravind Oct 17 '18 at 10:10
  • I should have imported uuid in react, and just called the uuid.vx(); your answer helped me understand the concept. Thanks. But in react if linter is enabled, it causes troubles. – Uzair Khan Oct 17 '18 at 10:11
  • 2
    Look into this https://stackoverflow.com/questions/9132772/lazy-loading-in-node-js if you want more details about using require inside functions. – Aravind Oct 17 '18 at 10:12
2

Just in case you would like to use uuid v4, this is how you can import it in react.

import uuid from 'uuid/v4'
Bassem
  • 3,582
  • 2
  • 24
  • 47
1
import React from "react";
import ReactDOM from "react-dom";
import * as uuid from "uuid";

function App() {
  return (
    <div className="App">
      <h1>{uuid.v4()}</h1>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Gucal
  • 842
  • 1
  • 11
  • 19
1

Using React with typescript version 4.5.0 or higher.

  1. Run: npm install --save @types/uuid

  2. Create directory "@types" in root folder with file "allTypes.d.ts" and add there

    declare module "uuid";

  3. In ts.config.json under compilerOptions add:

    "typeRoots": ["./node_modules/@types","./@types" ]

  4. Rerun your app and import where necessary
    import { v4 as uuidv4 } from "uuid";

szachMati
  • 196
  • 2
  • 12
0

In react use import.

In Nodejs project use 'require'.

If you want to use import in normal nodejs project "babel" is needed to setup.

ZF007
  • 3,708
  • 8
  • 29
  • 48
Ping Woo
  • 1,423
  • 15
  • 21
0

For React JS:

import { v1 as uuidv1 } from 'uuid';
uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d'
Nawab Ali
  • 176
  • 2
  • 7
  • Please describe the resolution in more detail with more insights like explaining the actual reason, add you working code snippet and steps to perform to eradicate the issues. For more details visit StackOverflow's guidelines. – Kapil Raghuwanshi May 08 '20 at 08:51
0

you can import in different ways

1----From the command line Installing

npm i react-uuid
import uuid from 'react-uuid'

and use for key variable like below

key={uuid()}

2---- A better way I always use is

first, install

npm install uuid

then import

import { v1 as uuidv1 } from 'uuid';

and use

uuidv1();

for more details read

0

you must go to this folder => your drive:/your projectfolder/node_modules/uuid/dist/v1 and see your uuid's folder by defult this is in top folder

import UUID From 'uuid/dist/v1'
Saeid
  • 422
  • 4
  • 9
0

Generate Unique ID in JavaScript using UUID

  1. make sure your at root run ls if your not sure look for package.json

  2. run npm i uuid

  3. to use it in the file you need

const {v4: uuidv4} = require('uuid')

now for the hard part if your using a route such as

controller.upload = (req, res) => {
    const id = uuidv4() // each upload will have a uuid thats random add your logic 
}

reference

Joshua
  • 589
  • 1
  • 5
  • 19
0

If what you are trying to do is to display a list of component items, you might consider this pattern:

import React from 'react'
import {v4 as uuidv4} from 'uuid'

const Project = ({title}) =>{
    return(
        <li>{title}</li>
    )
}
const ProjectList = ({projects}) => {
  return (
    <div>
        <ul>
            {
                projects.map(project => <Project title={project.title} key={uuidv4()}/>)
            }
        </ul>
    </div>
  )
}

export default ProjectList

Bello Shehu
  • 149
  • 5
  • Never use random values as a key. Use a property of the data you’re mapping over, or, as a last resort, use the index. – Remco Haszing Feb 03 '23 at 09:49