@alexrah/react-use-id-hook
v1.1.1
Published
## Disclaimer This is a fork of https://www.npmjs.com/package/react-use-id-hook which adds the ability to set a custom prefix to the generated ids
Downloads
10
Readme
react-use-id-hook
Disclaimer
This is a fork of https://www.npmjs.com/package/react-use-id-hook which adds the ability to set a custom prefix to the generated ids
Description
This is a tiny hook to create consisent id strings while rendering React, both when doing SSR and normally.
This is useful for creating unique id
attributes for DOM elements.
API
<IdProvider [prefix="id-"] />
This provider provides the id state. Your app needs to be wrapped with it.
useId()
This hook returns a unique id that remains consistent on re-render
useGetId()
This hook returns a function that returns unique ids. To use it, the same rule applies as for hooks:
always call it in the same order, without control flow
Installation
- Install the
react-use-id-hook
NPM package with your favorite package manager. - Wrap your top-level component with
<IdProvider>
- In your components, use
useId()
oruseGetId()
as appropriate.
Example
const CheckBox = ({value, onChange}) => {
const id = useId()
return (
<>
<input
id={id}
type="checkbox"
checked={value}
onChange={(ev) => onChange(ev.target.checked)}
/>
<label htmlFor={id}>Click me</label>
</>
)
}