UNPKG

1.68 kBPlain TextView Raw
1'use strict';
2/**
3 * imported from react-native
4 */
5
6import type { MutableRefObject } from 'react';
7
8/* eslint-disable */
9/**
10 * This is a helper function for when a component needs to be able to forward a ref
11 * to a child component, but still needs to have access to that component as part of
12 * its implementation.
13 *
14 * Its main use case is in wrappers for native components.
15 *
16 * Usage:
17 *
18 * class MyView extends React.Component {
19 * _nativeRef = null;
20 *
21 * _setNativeRef = setAndForwardRef({
22 * getForwardedRef: () => this.props.forwardedRef,
23 * setLocalRef: ref => {
24 * this._nativeRef = ref;
25 * },
26 * });
27 *
28 * render() {
29 * return <View ref={this._setNativeRef} />;
30 * }
31 * }
32 *
33 * const MyViewWithRef = React.forwardRef((props, ref) => (
34 * <MyView {...props} forwardedRef={ref} />
35 * ));
36 *
37 * module.exports = MyViewWithRef;
38 */
39/* eslint-enable */
40
41type ForwardedRef<T> = () => MutableRefObject<T> | ((ref: T) => void);
42
43function setAndForwardRef<T>({
44 getForwardedRef,
45 setLocalRef,
46}: {
47 getForwardedRef: ForwardedRef<T>;
48 setLocalRef: (ref: T) => void;
49}): (ref: T) => void {
50 return function forwardRef(ref: T) {
51 const forwardedRef = getForwardedRef();
52
53 setLocalRef(ref);
54
55 // Forward to user ref prop (if one has been specified)
56 if (typeof forwardedRef === 'function') {
57 // Handle function-based refs. String-based refs are handled as functions.
58 forwardedRef(ref);
59 } else if (typeof forwardedRef === 'object' && forwardedRef != null) {
60 // Handle createRef-based refs
61 forwardedRef.current = ref;
62 }
63 };
64}
65
66export default setAndForwardRef;