@navikt/ds-react
Version:
React components from the Norwegian Labour and Welfare Administration.
37 lines • 1.44 kB
JavaScript
"use client";
//https://github.com/mui/material-ui/blob/master/packages/mui-utils/src/useId.ts
import React, { useEffect, useState } from "react";
let globalId = 0;
function useGlobalId(idOverride) {
const [defaultId, setDefaultId] = useState(idOverride);
const id = idOverride || defaultId;
useEffect(() => {
if (defaultId == null) {
// Fallback to this default id when possible.
// Use the incrementing value for client-side rendering only.
// We can't use it server-side.
// If you want to use random values please consider the Birthday Problem: https://en.wikipedia.org/wiki/Birthday_problem
globalId += 1;
setDefaultId(`aksel-id-${globalId}`);
}
}, [defaultId]);
return id;
}
const maybeReactUseId = React["useId" + "" // Workaround for https://github.com/webpack/webpack/issues/14814
];
/**
*
* @example <div id={useId()} />
* @param idOverride
* @returns {string}
*/
export function useId(idOverride) {
var _a;
if (maybeReactUseId !== undefined) {
const reactId = maybeReactUseId();
return idOverride !== null && idOverride !== void 0 ? idOverride : reactId.replace(/(:)/g, "");
}
// eslint-disable-next-line react-hooks/rules-of-hooks -- `useId` is invariant at runtime.
return (_a = useGlobalId(idOverride)) !== null && _a !== void 0 ? _a : "";
}
//# sourceMappingURL=useId.js.map