UNPKG

@navikt/ds-react

Version:

React components from the Norwegian Labour and Welfare Administration.

39 lines 2.59 kB
import cl from "clsx"; import { useContext } from "react"; import { useId } from "../util/hooks/index.js"; import { FieldsetContext } from "./fieldset/context.js"; /** * Handles props and their state for various form-fields in context with Fieldset */ export const useFormField = (props, prefix) => { var _a, _b, _c; const { size, error, errorId: propErrorId } = props; const fieldset = useContext(FieldsetContext); const genId = useId(); const id = (_a = props.id) !== null && _a !== void 0 ? _a : `${prefix}-${genId}`; const errorId = propErrorId !== null && propErrorId !== void 0 ? propErrorId : `${prefix}-error-${genId}`; const inputDescriptionId = `${prefix}-description-${genId}`; const disabled = (fieldset === null || fieldset === void 0 ? void 0 : fieldset.disabled) || props.disabled; const readOnly = (((fieldset === null || fieldset === void 0 ? void 0 : fieldset.readOnly) || props.readOnly) && !disabled) || undefined; const hasError = !disabled && !readOnly && !!(error || (fieldset === null || fieldset === void 0 ? void 0 : fieldset.error)); const showErrorMsg = !disabled && !readOnly && !!error && typeof error !== "boolean"; const ariaInvalid = Object.assign({}, (hasError ? { "aria-invalid": true } : {})); if ((props === null || props === void 0 ? void 0 : props.required) && process.env.NODE_ENV !== "production") { console.warn("Aksel: Use of 'required' in form-elements is heavily discuouraged. Docs about why here:"); console.warn("https://aksel.nav.no/god-praksis/artikler/obligatoriske-og-valgfrie-skjemafelter#h3bfe00453471"); } return { showErrorMsg, hasError, errorId, inputDescriptionId, size: (_b = size !== null && size !== void 0 ? size : fieldset === null || fieldset === void 0 ? void 0 : fieldset.size) !== null && _b !== void 0 ? _b : "medium", readOnly, inputProps: Object.assign(Object.assign({ id }, ariaInvalid), { "aria-describedby": cl(props["aria-describedby"], { [inputDescriptionId]: !!(props === null || props === void 0 ? void 0 : props.description) && typeof (props === null || props === void 0 ? void 0 : props.description) === "string", [errorId]: showErrorMsg, [(_c = fieldset === null || fieldset === void 0 ? void 0 : fieldset.errorId) !== null && _c !== void 0 ? _c : ""]: hasError && !!(fieldset === null || fieldset === void 0 ? void 0 : fieldset.error), }) || undefined, disabled }), }; }; //# sourceMappingURL=useFormField.js.map