A React context & hook for managing and asserting the uniqueness of explicitly defined DOM ids.
The hook performs the following operations automatically:
Adds the ID to the provided registry on mount.
Removes the ID from the provided registry on unmount.
Replaces the ID in the provided registry when its value changes.
Either throws an error or logs a warning when a duplicate ID is found within the provided registry.
Optionally throws an error for a required ID if it was not given a value.
[!IMPORTANT]
If your app integrates multiple Documents, you'll need to create and provide a registry for each since their ids do not overlap.
Consumer Usage
To install:
npm i react-element-id
To import into your SPA:
import { createElementIdRegistry, ElementIdRegistryContext, WARN } from 'react-element-id';// This will not directly break your app if a duplicate is found at runtimeconst registry = createElementIdRegistry(WARN);renderToDOM( <ElementIdRegistryContext.Provider value={registry}> <App /> </ElementIdRegistryContext.Provider>);
To import into your SSR/SSG MPA:
import { createElementIdRegistry, ElementIdRegistryContext, THROW } from 'react-element-id';// This will intentionally fail your build when a duplicate is foundconst registry = createElementIdRegistry(THROW);renderToString( <ElementIdRegistryContext.Provider value={registry}> <App /> </ElementIdRegistryContext.Provider>);