Created
May 13, 2020 08:06
-
-
Save philippeauriach/70fd2a47afb0dc717d354176bfc688b3 to your computer and use it in GitHub Desktop.
React: Using a forwarded ref in a forwarded component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Usecase : you want a generic component for a text input with a title, | |
you create a component accepting a title props, returning a TextView along a TextInput. | |
For ease of use, this new component uses React.forwardRef to allow passing a ref to the TextInput. | |
BUT, you want this generic component to handle the case "when I click the title I focus the input), | |
so you need to "intercept" the forward ref | |
*/ | |
interface MyCustomInputProps { | |
title: string | |
} | |
export const MyCustomInput = React.forwardRef<TextInput, MyCustomInputProps> = ({title}, ref) => { | |
const internalRef = React.useRef<TextInput>(null) | |
const onPressTitle = React.useCallback(() => { | |
try { | |
// ref has the following type: React.Ref<T> which resolves as | |
// type React.Ref<T> = ((instance: T | null) => void) | RefObject<T> | null | |
// so to be sure to handle all cases we should try to cast into the method variant too | |
const castedRef = ref as React.RefObject<TextInput> | null | |
castedRef?.current?.focus() | |
} catch (err) { | |
console.info(err) | |
} | |
internalRef.current?.focus() | |
}) | |
return ( | |
<View> | |
<Text onPress={onPressTitle}>{title}</Text> | |
<TextInput ref={ref || internalRef}/> | |
</View> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment