@navikt/ds-react
Version:
React components from the Norwegian Labour and Welfare Administration.
34 lines • 1.68 kB
JavaScript
/**
* Give warnings based on component composition (which slot/parent a child is rendered in).
*
* Used when child components need to know which slot/parent they are rendered in
* (e.g. `FormSummary.Header` vs `FormSummary.Footer`) and should warn or error in development
* if placed in a discouraged or forbidden slot.
*
* Usage:
* - Wrap slot components with <CompositionWarning.Root name="FormSummary.Header">...</CompositionWarning.Root>
* - In child: `<CompositionWarning.Forbidden name="FormSummary.Header" />` to forbid slot.
*
* This is guidance only: warnings are logged to the console in development, never enforced at runtime.
*/
import React, { useEffect, useRef } from "react";
import { Slot } from "../../slot/Slot.js";
import { createContext } from "../create-context.js";
const isDev = process.env.NODE_ENV !== "production";
const [CompositionWarning, useCompositionWarning] = createContext({
errorMessage: "useCompositionWarning() must be used within <CompositionWarning />",
});
function CompositionWarningForbidden({ children, name, message, }) {
var _a;
const compositionName = (_a = useCompositionWarning(false)) === null || _a === void 0 ? void 0 : _a.name;
const elementRef = useRef(null);
useEffect(() => {
if (!isDev || !compositionName || name !== compositionName) {
return;
}
console.warn(`[Aksel] ${message}\nElement: `, elementRef.current);
}, [compositionName, name, message]);
return React.createElement(Slot, { ref: elementRef }, children);
}
export { CompositionWarningForbidden as Forbidden, CompositionWarning as Root };
//# sourceMappingURL=CompositionWarning.js.map