GitXplorerGitXplorer
T

react-id-generator

public
50 stars
5 forks
6 issues

Commits

List of commits on branch master.
Unverified
ffa883ea886be427bda8eab62b6b3f071c06e64d

build(deps): bump json5 from 2.1.0 to 2.2.3

ddependabot[bot] committed 2 years ago
Unverified
97e5bf6d8df59aa21363ea314ca612d22966cb50

build(deps): bump minimist from 1.2.5 to 1.2.6

ddependabot[bot] committed 3 years ago
Unverified
b101360c690b0a5fa4c2330d54f634b07b878cbc

build(deps): bump ansi-regex from 4.1.0 to 4.1.1

ddependabot[bot] committed 3 years ago
Unverified
ae2681594513bc8c0636ca7688beb18c05d0ca6a

build(deps): bump ajv from 6.10.2 to 6.12.6

ddependabot[bot] committed 3 years ago
Unverified
b41ed913d07d492b111f5e3b89becd2e9b3a786d

build(deps): bump trim-off-newlines from 1.0.1 to 1.0.3

ddependabot[bot] committed 3 years ago
Unverified
9eda3f27ea3eb01f648bcb9a642246e91e21f30e

build(deps-dev): bump next from 11.1.1 to 12.1.0 in /example

ddependabot[bot] committed 3 years ago

README

The README file for this repository.

react-id-generator npm version Build Status ts

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 app:
Edit react-id-generator-example

Basic example:

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:

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:

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

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

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

you can also set a prefix for them:

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:

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:

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

Props go to people that shared their ideas in this SO topic.