Skip to content

Instantly share code, notes, and snippets.

@pie6k
Created October 23, 2019 10:02
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pie6k/b4717f392d773a71f67e110b42927fea to your computer and use it in GitHub Desktop.
Save pie6k/b4717f392d773a71f67e110b42927fea to your computer and use it in GitHub Desktop.
forwardRef hook
import React, { useRef, forwardRef, Ref, useEffect } from 'react';
import { TextInputProps, TextInput } from 'react-native';
import styled from 'styled-components/native';
interface Props extends TextInputProps {
showEditLabel?: boolean;
}
const Input = styled.TextInput``;
function useShareForwardedRef<T>(forwardedRef: Ref<T>) {
// final ref that will share value with forward ref. this is the one we will attach to components
const innerRef = useRef<T>(null);
useEffect(() => {
// after every render - try to share current ref value with forwarded ref
if (!forwardedRef) {
return;
}
if (typeof forwardedRef === 'function') {
forwardedRef(innerRef.current);
return;
} else {
// @ts-ignore
// by default forwardedRef.current is readonly. Let's ignore it
forwardedRef.current = innerRef.current;
}
});
return innerRef;
}
// now we have some custom component, where we want to forward and use ref
export const SuperInput = forwardRef<TextInput, Props>(
function(props: Props, ref) {
const innerRef = useShareForwardedRef(ref);
useEffect(() => {
// we can use ref here! it is also forwarded
innerRef.current.focus();
})
return (
<Input
ref={innerRef}
{...props}
/>
);
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment