UNPKG

1.72 kBJavaScriptView Raw
1/*
2 * Copyright 2023 Palantir Technologies, Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16import * as React from "react";
17/**
18 * Keep track of a control's checked state in both controlled and uncontrolled modes
19 */
20export function useCheckedControl(props) {
21 var _a;
22 var _b = React.useState(function () { var _a; return (_a = props.defaultChecked) !== null && _a !== void 0 ? _a : false; }), checkedStateForUncontrolledMode = _b[0], setChecked = _b[1];
23 // If the checked prop is passed, this input is in "controlled mode" and
24 // should always reflect the value of the controlled prop. Any internal
25 // state tracked for "uncontrolled mode" should be ignored.
26 var checked = (_a = props.checked) !== null && _a !== void 0 ? _a : checkedStateForUncontrolledMode;
27 var onChange = React.useCallback(function (e) {
28 var _a;
29 setChecked(function (c) { return !c; });
30 (_a = props.onChange) === null || _a === void 0 ? void 0 : _a.call(props, e);
31 },
32 // eslint-disable-next-line react-hooks/exhaustive-deps
33 [props.onChange]);
34 return { checked: checked, onChange: onChange };
35}
36//# sourceMappingURL=useCheckedControl.js.map
\No newline at end of file