@primer/react
Version:
An implementation of GitHub's Primer Design System using React
61 lines (60 loc) • 2.33 kB
JavaScript
import { useProvidedRefOrCreate } from "../hooks/useProvidedRefOrCreate.js";
import useIsomorphicLayoutEffect from "../utils/useIsomorphicLayoutEffect.js";
import shared_module_css_default from "./shared.module.css.js";
import { CheckboxGroupContext } from "../CheckboxGroup/CheckboxGroupContext.js";
import Checkbox_module_css_default from "./Checkbox.module.css.js";
import { clsx } from "clsx";
import { jsx } from "react/jsx-runtime";
import React, { useContext, useEffect } from "react";
//#region src/Checkbox/Checkbox.tsx
/**
* An accessible, native checkbox component
*/
const Checkbox = /*#__PURE__*/ React.forwardRef(({ checked, className, defaultChecked, indeterminate, disabled, onChange, required, validationStatus, value, ["data-component"]: dataComponent, ...rest }, ref) => {
const checkboxRef = useProvidedRefOrCreate(ref);
const checkboxGroupContext = useContext(CheckboxGroupContext);
const handleOnChange = (e) => {
checkboxGroupContext.onChange && checkboxGroupContext.onChange(e);
onChange && onChange(e);
if (indeterminate && checkboxRef.current) {
checkboxRef.current.indeterminate = true;
checkboxRef.current.setAttribute("aria-checked", "mixed");
}
};
const inputProps = {
type: "checkbox",
disabled,
ref: checkboxRef,
checked: indeterminate ? false : checked,
defaultChecked,
required,
["aria-required"]: required ? "true" : "false",
["aria-invalid"]: validationStatus === "error" ? "true" : "false",
onChange: handleOnChange,
value,
name: value,
...rest
};
useIsomorphicLayoutEffect(() => {
if (checkboxRef.current) checkboxRef.current.indeterminate = indeterminate || false;
}, [
indeterminate,
checked,
checkboxRef
]);
useEffect(() => {
const { current: checkbox } = checkboxRef;
if (!checkbox) return;
if (indeterminate) checkbox.setAttribute("aria-checked", "mixed");
else checkbox.setAttribute("aria-checked", checkbox.checked ? "true" : "false");
});
return /*#__PURE__*/ jsx("input", {
...inputProps,
"data-component": dataComponent !== null && dataComponent !== void 0 ? dataComponent : "Checkbox",
className: clsx(className, shared_module_css_default.Input, Checkbox_module_css_default.Checkbox)
});
});
Checkbox.displayName = "Checkbox";
Checkbox.__SLOT__ = Symbol("Checkbox");
//#endregion
export { Checkbox as default };