Search code examples
reactjstypescriptrefuse-ref

useRef not working [TypeError: null is not an object (evaluating 'filed2.current.focus')]


I'm trying to focus on the next input field whenever the next button is pressed on the keyboard.

From the react native documentation I've understood that we need to use the useRef hook. However following the document

TypeError: null is not an object (evaluating 'filed2.current.focus')

I'm using the latest version of all packages, with a new react native app with the typescript template.

here is the bit of code that I have so far:

import React, {useRef} from 'react';

...

  const filed1 = useRef(null);
  const filed2 = useRef(null);

  const onButtonClick = () => {
    filed2.current.focus();
  };

  return (
    <>
      <FormInputPassword
        ref={filed1}
        returnKeyType="next"
        onSubmitEditing={onButtonClick}
        blurOnSubmit={false}
      />
      <FormInputPassword
        ref={filed2}
        returnKeyType="done"
        blurOnSubmit={false}
      />
    </ >
  );

Edit:


function FormInputPassword(props) {
  return (
      <FormInputView>
        <Input {...props} />
      </FormInputView>
  );
}


FormInputPassword.defaultProps = {
  blurOnSubmit: true,
  autoCorrect: false,
  editable: true,
};

Solution

  • Function components can't have ref instance.

    React.forwardRef((props,ref) => {
      return (
          <FormInputView ref={ref}>
            <Input {...props} />
          </FormInputView>
      );
    });