All Articles

How I generate UUIDs in TypeScript for development stages.

⁉️ Why?

I need to use UUIDs for child items in list components. UUIDs will be provided by API in most prod cases. I prefer to use the most simple and performant way to generate GUID-like unique identifiers.

💻 How?

This is a totally non-compliant but useful snippet to generate an ASCII-safe UUIDs in TypeScript:

export const uuid = (): string => {
  return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
};

📌 Example!

The simple React component example:

import React from 'react';
import './styles.css';

export const App: React.FunctionComponent = () => {
  const fruits = [
    { id: uuid(), type: 'apple' },
    { id: uuid(), type: 'orange' },
    { id: uuid(), type: 'mango' }
  ];
  return (
    <div className="App">
      <h1>Fruits:</h1>
      <ul>
        {fruits.map(fruit => (
          <li key={fruit.id}>{fruit.type}</li>
        ))}
      </ul>
    </div>
  );
};

const uuid = (): string => {
  return (
    Math.random()
      .toString(36)
      .substring(2, 15) +
    Math.random()
      .toString(36)
      .substring(2, 15)
  );
};