Use npm uuid in reactjs
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.
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 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.