# react-id-generator

> Simple and universal HTML-id generator for React.

Latest version **3.0.2** (published 2021-09-07) · MIT license · 0 weekly downloads

## Install

```sh
npm install react-id-generator
pnpm add react-id-generator
yarn add react-id-generator
bun add react-id-generator
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 3.0.2 |
| Published | 2021-09-07 |
| First published | 2017-12-04 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 0 |
| Unpacked size | 9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 50 |
| Author | Tomasz Mularczyk |
| Maintainers | tomekmularczyk |
| Keywords | id, react, react-id, id-generator |

## Links

- npm: https://www.npmjs.com/package/react-id-generator
- Repository: https://github.com/Tomekmularczyk/react-id-generator
- Homepage: https://github.com/Tomekmularczyk/react-id-generator#readme
- Issues: https://github.com/Tomekmularczyk/react-id-generator/issues
- npm.io page: https://npm.io/package/react-id-generator

## Alternatives

- [@sindresorhus/slugify](https://npm.io/package/@sindresorhus/slugify.md) — 3.7M weekly downloads
- [solid-js](https://npm.io/package/solid-js.md) — 2.7M weekly downloads
- [expo-glass-effect](https://npm.io/package/expo-glass-effect.md) — 2.5M weekly downloads
- [nanoassert](https://npm.io/package/nanoassert.md) — 780.8K weekly downloads
- [@ffmpeg/ffmpeg](https://npm.io/package/@ffmpeg/ffmpeg.md) — 529.5K weekly downloads

## Recent versions

- 3.0.2 (latest) — 2021-09-07
- 3.0.1 — 2020-07-11
- 3.0.0 — 2019-11-10
- 2.0.2 — 2019-11-10
- 2.0.1 — 2019-11-10
- 2.0.0 — 2019-07-15
- 1.0.0 — 2019-07-14
- 0.2.0 — 2019-07-11
- 0.1.6 — 2018-04-23
- 0.1.5 — 2018-04-22
- 0.1.3 — 2018-04-09
- 0.1.2 — 2018-04-03
- 0.1.1 — 2018-03-30
- 0.1.0 — 2018-03-30
- 0.0.1 — 2017-12-04

## README

# react-id-generator [![npm version][npm-badge]][npm-link] [![Build Status][ci-badge]][ci-link] [![ts][ts-badge]][ts-link]

Generate unique id's in React components (e.g. for accessibility).

**Features:**

- Generates unique but predictable id's ✔︎
- Works with server-side rendering ✔︎
- TypeScript support ✔︎

See an example with [Next.js](https://nextjs.org/) app:
<br />
[![Edit react-id-generator-example][cs-button]](https://codesandbox.io/s/react-id-generator-example-udjzm?fontsize=14)

### Basic example:

```jsx
import React from "react";
import nextId from "react-id-generator";

class RadioButton extends React.Component {
  htmlId = nextId();

  render() {
    const { children, ...rest } = this.props;
    return (
      <div>
        <label htmlFor={this.htmlId}>{children}</label>
        <input id={this.htmlId} type="radio" {...rest} />
      </div>
    );
  }
}

// Or with hooks:
import React from "react";
import { useId } from "react-id-generator";

const RadioButton = ({ children, ...rest }) => {
  const [htmlId] = useId();

  return (
    <div>
      <label htmlFor={htmlId}>{children}</label>
      <input id={htmlId} type="radio" {...rest} />
    </div>
  );
};
```

Each instance of `RadioButton` will have unique `htmlId` like: _id-1_, _id-2_, _id-3_, _id-4_ and so on.

### `nextId`

This is simple function that returns unique id that's incrementing on each call. It can take an argument which will be used as prefix:

```js
import nextId from "react-id-generator";

const id1 = nextId(); // id: id-1
const id2 = nextId("test-id-"); // id: test-id-2
const id3 = nextId(); // id: id-3
```

NOTE: Don't initialize `htmlId` in React lifecycle methods like _render()_. `htmlId` should stay the same during component lifetime.

### `useId`

This is a hook that will generate id (or id's) which will stay the same across re-renders - it's a function component equivalent of `nextId`. However, with some additional features.

By default it will return an array with single element:

```jsx
const idList = useId(); // idList: ["id1"]
```

but you can specify how many id's it should return:

```jsx
const idList = useId(3); // idList: ["id1", "id2", "id3"]
```

you can also set a prefix for them:

```jsx
const idList = useId(3, "test"); // idList: ["test1", "test2", "test3"]
```

**New id's will be generated only when one of the arguments change.**

### `resetId`

This function will reset the id counter. Main purpose of this function is to avoid warnings thrown by React durring server-side rendering (and also avoid counter exceeding `Number.MAX_SAFE_INTEGER`):

> Warning: Prop `id` did not match. Server: "test-5" Client: "test-1"

While in browser generator will always start from "1", durring SSR we need to manually reset it before generating markup for client:

```javascript
import { resetId } from "react-id-generator";

server.get("*", (req, res) => {
  resetId();

  const reactApp = (
    <ServerLocation url={req.url}>
      <StyleSheetManager sheet={sheet.instance}>
        <Provider store={store}>
          <App />
        </Provider>
      </StyleSheetManager>
    </ServerLocation>
  );
  const html = renderToString(reactApp);

  res.render("index", { html });
}
```

This should keep ids in sync both in server and browser generated markup.

### `setPrefix`

You can set prefix globally for every future id that will be generated:

```javascript
import { setPrefix } from "react-id-generator";

setPrefix("test-id-");

const id1 = nextId(); // id: test-id-1
const id2 = nextId(); // id: test-id-2
const id3 = nextId("local"); // id: local-3 - note that local prefix has precedence
```

### Running example in the repo:

1. First build the package: `yarn build && yarn build:declarations`
2. Go to `example/` directory and run `yarn dev`

<br/>

Props go to people that shared their ideas in [this SO topic](https://stackoverflow.com/q/29420835/4443323).

[npm-badge]: https://badge.fury.io/js/react-id-generator.svg
[npm-link]: https://badge.fury.io/js/react-id-generator
[ci-badge]: https://travis-ci.org/Tomekmularczyk/react-id-generator.svg?branch=master
[ci-link]: https://travis-ci.org/Tomekmularczyk/react-id-generator
[ts-badge]: https://badges.frapsoft.com/typescript/code/typescript.svg?v=101
[ts-link]: https://www.typescriptlang.org/
[cs-button]: https://codesandbox.io/static/img/play-codesandbox.svg

---
_Source: https://npm.io/package/react-id-generator · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
