How to setup/use ref correctly for a themed functional component in typescript + react native

Viewed 720

Main Goal: I have two TextInput and I want to simulate the return click on first textInput to set focus to the next textInput.

Lets start with the setup (using typescript)

I have a themed TextInput with some color settings as shown below. I setup/use the forwardRef to pass-on the ref if provided. Of what I could read, this seems to be the right way. but maybe this is wrong.

export type TextInputProps = ThemeProps & RNTextInput['props'];

export const TextInput = React.forwardRef<RNTextInput, TextInputProps>((props, ref) => {
...
return <RNTextInput style={[{ backgroundColor, color }, style]} {...otherProps} ref={ref} />;
}

Now on my screen, I am using this object and on the completion of typing on first input, I wanted to set focus on this one. The code looks like this..

const inputSecound = React.useRef<typeof TextInput>();
const handleFirstTextComplete = () => {
    inputSecound.current.focus() // This does not work
}
...
<TextInput onSubmitEditing={handleFirstTextComplete} ...>
<TextInput ... ref={inputSecound}> //This also complains

Any idea how to achieve this correctly in functional components + custom components + typescript.

A sample snack is available here if you wants to see the complete setup in action. https://snack.expo.io/@varesh.tapadia/useref-and-useforwardref

1 Answers

This should solve your issue.

interface CustomInputProps {
    handleCompletion: () => void;
}

const CustomInput = React.forwardRef<HTMLInputElement, CustomInputProps>((props, ref) => {
    return <input ref={ref}/>;
});

const Parent = () => {
    const secondInputRef = useRef<HTMLInputElement>(null);
    const handleCompletion = () => {
        secondInputRef?.current?.focus();
    }
    return (<>
        <CustomInput handleCompletion={handleCompletion} />
        <CustomInput ref={secondInputRef} handleCompletion={() => {}} />
    </>);
}
Related