@fremtind/jkl-feedback-react
Version:
Jøkul react feedback component
81 lines (80 loc) • 2.31 kB
JavaScript
import { Checkbox } from "@fremtind/jkl-checkbox-react";
import { FieldGroup } from "@fremtind/jkl-input-group-react";
import React, { useEffect, useRef } from "react";
import { useFollowUpContext } from "../followup/followupContext";
import { useMainQuestionContext } from "../main-question/mainQuestionContext";
const CheckboxQuestion = ({
label,
name,
options,
helpLabel,
autoFocus = false
}) => {
const followupContext = useFollowUpContext();
const feedbackContext = useMainQuestionContext();
const context = followupContext || feedbackContext;
const ref = useRef(null);
useEffect(() => {
if (autoFocus && ref.current) {
ref.current.focus();
}
}, [autoFocus, ref]);
const handleChange = (event) => {
const { value } = event.target;
const matchingOption = options == null ? void 0 : options.find(
(option) => option.value.toString() === value
);
if (!matchingOption)
return;
if (!(context == null ? void 0 : context.currentValue)) {
context == null ? void 0 : context.setCurrentValue([matchingOption]);
return;
}
if (Array.isArray(context == null ? void 0 : context.currentValue)) {
const found = context.currentValue.find(
(option) => option === matchingOption
);
if (found) {
context.setCurrentValue(
(oldValues) => oldValues.filter(
(option) => option !== found
)
);
} else {
context.setCurrentValue((oldValues) => [
...oldValues,
matchingOption
]);
}
}
};
if (!context) {
console.error(
"Questions must be used inside a Followup or Feedback context provider"
);
return null;
}
return /* @__PURE__ */ React.createElement(
FieldGroup,
{
labelProps: { variant: "large" },
legend: label,
helpLabel
},
options == null ? void 0 : options.map((option, i) => /* @__PURE__ */ React.createElement(
Checkbox,
{
key: "".concat(label, "-").concat(option.value),
name: name || label,
value: option.value.toString(),
onChange: handleChange,
ref: i === 0 ? ref : void 0
},
option.label
))
);
};
export {
CheckboxQuestion
};
//# sourceMappingURL=CheckboxQuestion.js.map