1

Let's say I have the input component, and a wrapper component called FancyInput.

I want to forward the inner Input ref through FancyInput, and also use the same ref inside the FancyInput, like calling ref.focus.

edit:

const SomeComponent = React.forwardRef((props, ref) => {
    const textInputRef = useRef<TextInput>(null)

    // how should I use textInputRef here, and also 
    // pass the ref to the FancyInput?

    return (
        <View>
           <FancyInput ref={textInputRef} />
       </View>
    )
})
vanenshi
  • 65
  • 2
  • 11
  • Does this answer your question? [How can I use forwardRef() in React?](https://stackoverflow.com/questions/66664209/how-can-i-use-forwardref-in-react) – Benjamin Apr 01 '22 at 21:14
  • @Benjamin no, i want to use the inner ref inside the HOC too, not just pass it through – vanenshi Apr 02 '22 at 05:15

1 Answers1

0

You need to wrap your component in React.forwardRef.

Here is a minimal code snippet.

const FancyInput = React.forwardRef((props, ref) => {
    return <TextInput ref={ref}></TextInput>
})

Suppose that we use it in a different component. Here is an example.

const SomeComponent = (props) => {
    const textInputRef = useRef<TextInput>(null)

    return (
        <View>
           <FancyInput ref={textInputRef} />
       </View>
    )
}

You can use the ref as usual in SomeComponent to call certain functions for the TextInput in FancyInput. The workflow is the same for other components.

David Scholz
  • 8,421
  • 12
  • 19
  • 34