signal-desktop/ts/hooks/useUniqueId.ts

25 lines
674 B
TypeScript
Raw Normal View History

2021-12-01 02:14:25 +00:00
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
2024-04-15 20:14:26 +00:00
import { useMemo, useState } from 'react';
2021-12-01 02:14:25 +00:00
import { v4 as uuid } from 'uuid';
export function useUniqueId(): string {
return useMemo(() => uuid(), []);
}
2024-04-15 20:14:26 +00:00
let nextElementId = 0;
export function useElementId(
namePrefix: string
): [id: string, selector: string] {
// Prefixed to avoid starting with a number (which is invalid in CSS selectors)
const [id] = useState(() => {
const currentId = nextElementId;
nextElementId += 1;
return `${namePrefix}-${currentId}`;
});
// Return the ID and a selector that can be used in CSS or JS
return [id, `#${id}`] as const;
}