Skip to content

Instantly share code, notes, and snippets.

@philippeauriach
Created May 13, 2020 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philippeauriach/70fd2a47afb0dc717d354176bfc688b3 to your computer and use it in GitHub Desktop.
Save philippeauriach/70fd2a47afb0dc717d354176bfc688b3 to your computer and use it in GitHub Desktop.
React: Using a forwarded ref in a forwarded component
/*
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