0.2.0 • Published 2 years ago

@valerie-makes/use-dom-id v0.2.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

use-dom-id

Build status MIT License NPM version Known Vulnerabilities

use-dom-id is a dependency-free React Hook for generating unique element IDs. It is compatible with both server-side and client-side rendering, including SSR with client-side hydration. It is particularly useful for HTML forms, where unique IDs are required for labels. It can also be used for other purposes, such as SVG definitions.

Examples

Form with single labelled input element

import useDomId from "@valerie-makes/use-dom-id";

function MyForm() {
  const [nameInputProps, useNameId] = useDomId<HTMLInputElement>();
  const nameLabelProps = useNameId((id) => ({ htmlFor: id }));

  return (
    <form>
      <label {...nameLabelProps}>Full Name</label>
      <input {...nameInputProps} type="text" />
    </form>
  );
}

Form with multiple labelled input elements

import useDomId from "@valerie-makes/use-dom-id";

function MyForm() {
  const [nameInputProps, useNameId] = useDomId<HTMLInputElement>();
  const nameLabelProps = useNameId((id) => ({ htmlFor: id }));

  const [emailInputProps, useEmailId] = useDomId<HTMLInputElement>();
  const emailLabelProps = useEmailId((id) => ({ htmlFor: id }));

  return (
    <form>
      <label {...nameLabelProps}>Full Name</label>
      <input {...nameInputProps} type="text" />

      <label {...emailLabelProps}>Email Address</label>
      <input {...emailInputProps} type="email" />
    </form>
  );
}

Usage

Outputs below are accurate for a server-rendering environment. The prefix id-client is used during client-side rendering to avoid collisions, except during hydration, in which IDs provided by the server are preserved.

useDomId<E extends Element>()

Generate a unique ID for a particular type of DOM element.

import useDomId from "@valerie-makes/use-dom-id";
const [idProps, useId] = useDomId<HTMLInputElement>();

// returns <input id="id-server-0" />
return <input {...idProps} />;

useDomId<E extends Element>(key: string)

Generate a unique ID for a particular type of DOM element, using a custom key.

import useDomId from "@valerie-makes/use-dom-id";
const [idProps, useId] = useDomId<HTMLInputElement>("my-key");

// returns <input id="my-key-server-0" />
return <input {...idProps} />;

useId<T>(generator: (id: string) => T)

Using a particular ID, generate props for additional elements.

const [idProps, useId] = useDomId<HTMLInputElement>();
const labelProps = useId((id) => ({ htmlFor: id }));

// returns <label htmlFor="id-server-0">My Label</label>
return <label {...labelProps}>My Label</label>;

resetRenderContext()

Resets render context variables, including the next ID. Useful to run before calling renderToString() in a server application such as Express, and before running tests, to ensure predictable outputs.

import { resetRenderContext } from "@valerie-makes/use-dom-id";
resetRenderContext(); // next ID is now 0

License

Copyright (c) 2022 Valerie Bailey

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.