UNPKG

2.32 kBJavaScriptView Raw
1/*
2 * Copyright 2020 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 */
16export function isRefObject(value) {
17 return value != null && typeof value !== "function";
18}
19export function isRefCallback(value) {
20 return typeof value === "function";
21}
22/**
23 * Assign the given ref to a target, either a React ref object or a callback which takes the ref as its first argument.
24 */
25export function setRef(refTarget, ref) {
26 if (isRefObject(refTarget)) {
27 refTarget.current = ref;
28 }
29 else if (isRefCallback(refTarget)) {
30 refTarget(ref);
31 }
32}
33/** @deprecated use mergeRefs() instead */
34export function combineRefs(ref1, ref2) {
35 return mergeRefs(ref1, ref2);
36}
37/**
38 * Utility for merging refs into one singular callback ref.
39 * If using in a functional component, would recomend using `useMemo` to preserve function identity.
40 */
41export function mergeRefs() {
42 var refs = [];
43 for (var _i = 0; _i < arguments.length; _i++) {
44 refs[_i] = arguments[_i];
45 }
46 return function (value) {
47 refs.forEach(function (ref) {
48 setRef(ref, value);
49 });
50 };
51}
52export function getRef(ref) {
53 var _a;
54 if (ref === null) {
55 return null;
56 }
57 return (_a = ref.current) !== null && _a !== void 0 ? _a : ref;
58}
59/**
60 * Creates a ref handler which assigns the ref returned by React for a mounted component to a field on the target object.
61 * The target object is usually a component class.
62 *
63 * If provided, it will also update the given `refProp` with the value of the ref.
64 */
65export function refHandler(refTargetParent, refTargetKey, refProp) {
66 return function (ref) {
67 refTargetParent[refTargetKey] = ref;
68 setRef(refProp, ref);
69 };
70}
71//# sourceMappingURL=refs.js.map
\No newline at end of file