@fremtind/jkl-feedback-react
Version:
Jøkul react feedback component
76 lines (75 loc) • 2.23 kB
JavaScript
import {
RadioButton,
RadioButtonGroup
} from "@fremtind/jkl-radio-button-react";
import React, {
useEffect,
useId,
useMemo,
useRef
} from "react";
import { useFollowUpContext } from "../followup/followupContext";
import { useMainQuestionContext } from "../main-question/mainQuestionContext";
const RadioQuestion = ({
label,
name,
options,
helpLabel,
autoFocus = false
}) => {
const followupContext = useFollowUpContext();
const feedbackContext = useMainQuestionContext();
const context = followupContext || feedbackContext;
const id = useId();
const numOptions = (options == null ? void 0 : options.length) || 0;
const ref = useRef(null);
useEffect(() => {
if (autoFocus && ref.current) {
ref.current.focus();
}
}, [autoFocus, ref]);
const handleChange = (e) => {
const option = options == null ? void 0 : options.find(
(option2) => option2.value.toString() === e.target.value
);
context == null ? void 0 : context.setCurrentValue(option);
};
const selectedValue = useMemo(
() => {
var _a;
return Array.isArray(context == null ? void 0 : context.currentValue) ? context == null ? void 0 : context.currentValue[0].value.toString() : (_a = context == null ? void 0 : context.currentValue) == null ? void 0 : _a.value.toString();
},
[context == null ? void 0 : context.currentValue]
);
if (!context) {
console.error(
"Questions must be used inside a Followup or Feedback context provider"
);
return null;
}
return /* @__PURE__ */ React.createElement(
RadioButtonGroup,
{
legend: label,
labelProps: { variant: "large" },
name: "".concat(id, "-").concat(name || label),
inline: numOptions < 3,
value: selectedValue || "",
onChange: handleChange,
helpLabel
},
options == null ? void 0 : options.map((option, i) => /* @__PURE__ */ React.createElement(
RadioButton,
{
ref: i === 0 ? ref : void 0,
key: "".concat(id, "-").concat(name || label, "-").concat(option.value),
label: option.label,
value: String(option.value)
}
))
);
};
export {
RadioQuestion
};
//# sourceMappingURL=RadioQuestion.js.map