UNPKG

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