|
Last change
on this file since a762898 was a762898, checked in by istevanoska <ilinastevanoska@…>, 6 months ago |
|
Added visualizations
|
-
Property mode
set to
100644
|
|
File size:
1.1 KB
|
| Line | |
|---|
| 1 | import { useId } from './useId';
|
|---|
| 2 |
|
|---|
| 3 | /**
|
|---|
| 4 | * A hook that generates a unique ID. It uses React.useId() in React 18+ for SSR safety
|
|---|
| 5 | * and falls back to a client-side-only unique ID generator for older versions.
|
|---|
| 6 | *
|
|---|
| 7 | * The ID will stay the same across renders, and you can optionally provide a prefix.
|
|---|
| 8 | *
|
|---|
| 9 | * @param [prefix] - An optional prefix for the generated ID.
|
|---|
| 10 | * @param [customId] - An optional custom ID to override the generated one.
|
|---|
| 11 | * @returns The unique ID.
|
|---|
| 12 | */
|
|---|
| 13 | export function useUniqueId(prefix, customId) {
|
|---|
| 14 | /*
|
|---|
| 15 | * We have to call this hook here even if we don't use the result because
|
|---|
| 16 | * rules of hooks demand that hooks are never called conditionally.
|
|---|
| 17 | */
|
|---|
| 18 | var generatedId = useId();
|
|---|
| 19 |
|
|---|
| 20 | // If a custom ID is provided, it always takes precedence.
|
|---|
| 21 | if (customId) {
|
|---|
| 22 | return customId;
|
|---|
| 23 | }
|
|---|
| 24 |
|
|---|
| 25 | // Apply the prefix if one was provided.
|
|---|
| 26 | return prefix ? "".concat(prefix, "-").concat(generatedId) : generatedId;
|
|---|
| 27 | }
|
|---|
| 28 |
|
|---|
| 29 | /**
|
|---|
| 30 | * The useUniqueId hook returns a unique ID that is either reused from external props or generated internally.
|
|---|
| 31 | * Either way the ID is now guaranteed to be present so no more nulls or undefined.
|
|---|
| 32 | */ |
|---|
Note:
See
TracBrowser
for help on using the repository browser.