{"id":19097975,"url":"https://github.com/hampusborgos/react-html-id","last_synced_at":"2026-03-04T21:02:26.510Z","repository":{"id":57333423,"uuid":"81303488","full_name":"hampusborgos/react-html-id","owner":"hampusborgos","description":"Provides unique IDs for HTML DOM elements.","archived":false,"fork":false,"pushed_at":"2018-11-28T10:17:39.000Z","size":16,"stargazers_count":26,"open_issues_count":4,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-10-02T10:52:43.467Z","etag":null,"topics":["html","react","reactjs"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hampusborgos.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-02-08T07:58:43.000Z","updated_at":"2021-07-05T13:59:25.000Z","dependencies_parsed_at":"2022-08-24T18:50:47.141Z","dependency_job_id":null,"html_url":"https://github.com/hampusborgos/react-html-id","commit_stats":null,"previous_names":["hjnilsson/react-html-id"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/hampusborgos/react-html-id","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hampusborgos%2Freact-html-id","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hampusborgos%2Freact-html-id/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hampusborgos%2Freact-html-id/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hampusborgos%2Freact-html-id/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hampusborgos","download_url":"https://codeload.github.com/hampusborgos/react-html-id/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hampusborgos%2Freact-html-id/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30092872,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-04T20:42:30.420Z","status":"ssl_error","status_checked_at":"2026-03-04T20:42:30.057Z","response_time":59,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["html","react","reactjs"],"created_at":"2024-11-09T03:43:41.421Z","updated_at":"2026-03-04T21:02:26.495Z","avatar_url":"https://github.com/hampusborgos.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# react-html-id\nA npm package that allows you to use unique html IDs for components\nwithout any dependencies on other libraries (obviously, you need to\nuse React in your project).\n\n## Purpose\n\nThis module allows you to set unique `id` tags on React HTML elements,\nmainly in order to connect labels to them but also for other HTML function\nthat require unique ids (`#references`).\n\n## Usage\n\nTo use the module, you first need to inject the extension into\nyour component. You do this via the `enableUniqueIds` function\n(which is the only function exposed by this module). Then you\ncan use `this.nextUniqueId()` to get a new identifier,\n`this.lastUniqueId()` to refer to that identifier again in the HTML,\nand `this.getUniqueId('name')` to get an identifier by name.\n\n    import uniqueId from 'react-html-id';\n    \n    class MyComponent {\n        constructor() {\n            super()\n\n            uniqueId.enableUniqueIds(this)\n        }\n\n        render () {\n            // Use nextUniqueId to create a new ID, and lastUniqueId to refer to the same ID again\n            return (\n                \u003cdiv className=\"form-group\"\u003e\n                    \u003clabel htmlFor={this.nextUniqueId()}\u003eName\u003c/label\u003e\n                    \u003cinput id={this.lastUniqueId()}\n                           type=\"text\"\n                           className=\"control\" /\u003e\n                \u003c/div\u003e\n            )\n        }\n    }\n\n### Why can't I just use a counter?\n\nThe problem with using a local counter in the render function is\nthat the *IDs will not be unique between different instances*.\n\n    class BadComponent {\n        render () {\n            var idCounter = 0;\n\n            // Do not do this!!\n            return (\n                \u003cdiv className=\"form-group\"\u003e\n                    \u003clabel htmlFor={'id-' + idCounter}\u003eName\u003c/label\u003e\n                    \u003cinput id={'id-' + idCounter}\n                           type=\"text\"\n                           className=\"control\" /\u003e\n                \u003c/div\u003e\n            )\n        }\n    }\n\nIf you put two instances of `BadComponent` in your React application,\nthey will both share the same IDs! This package ensures you will get\nunique IDs per instance of every component.\n\n### Does this work with server side rendering?\n\nIf you render your UI on the server in it's own process per request, you\ndo not need to anything extra, because the result of rendering will be\nidentical across the server and the client.\n\nHowever, if you render multiple different React components on the server\nusing `renderToString` (this is what a framework like Next.js does) you\nneed to reset the unique ID counter between each request to result in the\nsame IDs being generated for the client every time. You can do this using\nthe `resetUniqueIds()` API.\n\nThe easiest way to do this for Next.js is to create a component like this:\n\n    // PageWithUniqueIds.jsx\n    import { resetUniqueIds } from \"react-html-id\";\n\n    class PageWithUniqueIds extends React.Component {\n        componentWillMount() {\n            resetUniqueIds()\n        }\n\n        render() {\n            return this.props.children;\n        }\n    }\n\n    // index.jsx\n    class IndexPage extends React.Component {\n        render() {\n            return (\n                \u003cPageWithUniqueIds\u003e\n                    {/* Your application code as usual */}\n                \u003c/PageWithUniqueIds\u003e\n            );\n        }\n    }\n\nWrap ALL pages you create with this component. Because this component will\nbe rendered for every page, componentWillMount will be called once for both server and\nclient per page. This will reset the ID counter before the page is rendered.\nThe result is that the same IDs will be used both server side and client side.\n\nThis strategy will only work if you render entire pages server side. If you render\nindividual components, this library will be insufficient to solve your problem.\nThere is no simple way of guaranteeing that the ID counter is consistent between\nserver and client in that situation, without storing the information in the DOM\nfor those nodes.\n\n## API\n\n### enableUniqueIds(component, [instanceId])\n\nThis should be called from the constructor of the component that needs unique IDs,\npassing `this` as the first parameter. After calling this you can use `nextUniqueId`, `lastUniqueId` and `getUniqueId`\nby invoking them on `this`.\n\nThis call either adds a `componentWillUpdate` handler to the current component,\nor wraps the existing one. The package uses `componentWillUpdate` to reset the\nID counter every time the component re-renders.\n\n    class MyComponent {\n        constructor() {\n            super()\n\n            // Enable Unique ID support for this class\n            enableUniqueIds(this)\n        }\n\n        render() {\n            // ...\n        }\n    }\n\nThe second optional `instanceId` parameter specifies a string to use for _all_ instances of this component when\nconstructing unique IDs, as opposed to using a unique string for each instance. While this essentially defeats the\npurpose of this module when there are multiple instances of your component on the page, it's useful for snapshot-based\nunit testing, e.g. [Storyshots](https://github.com/storybooks/storybook/tree/master/addons/storyshots), where the\nindeterminate nature of test execution order might generate different unique IDs on each test run. In this case, you'll\nlikely want want to only use it when you're actually running the unit tests:\n\n    enableUniqueIds(this, (process.env.NODE_ENV === 'test') ? props.name : undefined)\n\n### Component.nextUniqueId()\n\nThis will returns a *new* unique id for the component. Repeatedly calling\nthis function will result in new IDs.\n\nIDs are consistent between renders, as long as the function is always called\nin the same order. This means there are *no DOM updates* necessary if you do\nnot remove calls to the function between renders.\n\n    render() {\n        var manyFields = ['firstName', 'lastName', 'address', 'postalCode', 'city']\n        \n        // Every label-input pair will have a unique ID \n        return (\n            \u003cform\u003e\n                {manyFields.map((field, index) =\u003e {\n                    return (\n                        \u003cdiv className=\"form-group\" key={index}\u003e\n                            \u003clabel htmlFor={this.nextUniqueId()}\u003eName\u003c/label\u003e\n                            \u003cinput id={this.lastUniqueId()}\n                                type=\"text\"\n                                className=\"control\" /\u003e\n                        \u003c/div\u003e\n                    )\n                })\n            \u003c/form\u003e\n        )\n    }\n\n### Component.lastUniqueId()\n\nReturns the same ID that was returned by the last call to `nextUniqueId`,\nthis is almost always necessary as you need to refer to the ID twice, once\nfor the label and once for the input.\n\n### Component.getUniqueId(identifier : String) \n\nThis always returns the same unique identifier, given the same name. \nThis is useful if the order of components makes it impossible or confusing \nto use `lastUniqueId` to refer to a component.\n\n    render() {\n        return (\n            \u003cdiv className=\"form-group\"\u003e\n                \u003clabel htmlFor={this.getUniqueId('input')}\u003eName\u003c/label\u003e\n                \u003cdiv className=\"help-block\"\n                        id={this.getUniqueId('help')}\u003e\n                    This should be your full name.\n                \u003c/div\u003e\n                \u003cinput id={this.getUniqueId('input')}\n                        type=\"text\"\n                        aria-describedby={this.getUniqueId('help')}\n                        className=\"control\" /\u003e\n            \u003c/div\u003e\n        )\n    }\n\nYou can of course also store the result of `nextUniqueId` into a variable\nto acheive the same result.\n\n### resetUniqueIds()\n\nThis resets the per-component counter of unique IDs. Call this before using\n`renderToString` on the **server**. If you call this on the client, make\nsure to only do so **once** per page render.\n\n    // Call before renderToString to reset the global ID counter\n    function renderAppServerSide(appProps) {\n        ReactHtmlId.resetUniqueIds()\n        ReactDOM.renderToString(\u003cApp props={...} /\u003e);\n    }\n\n## Credits\n\nThis package is brought to you by [Hampus Nilsson](https://hjnilsson.com).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhampusborgos%2Freact-html-id","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhampusborgos%2Freact-html-id","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhampusborgos%2Freact-html-id/lists"}