npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-id-generator

v3.0.2

Published

Simple and universal HTML-id generator for React.

Downloads

265,773

Readme

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.