'How can I pass focus to ref on other elements blur in TS

I have a form with a field and a button, I would like to make the button stand out on input's blur so I have placed a ref on a button

const btnRef = useRef<HTMLElement>(null);

and written function

  const passFocus = () => {
    btnRef.current?.focus();
  };

but on the button ref typescript has a problem saying

Type 'RefObject<HTMLElement>' is not assignable to type 'MutableRefObject<null>'.
  Types of property 'current' are incompatible.
    Type 'HTMLElement | null' is not assignable to type 'null'.
      Type 'HTMLElement' is not assignable to type 'null'.ts(2322)
Button.tsx(10, 3): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'

the button itself looks like so

 <Button
        color={COLORS.TERTIARY}
        textColor={COLORS.FONT_COLOR}
        onPress={handleSubmit((data) => onSubmit(data))}
        ref={btnRef}
      >
        Enter
      </Button>

If this is of any importance this is React Native



Solution 1:[1]

It's because in the first render ref is null and you add only HTMLElement for type so you should do below:

const btnRef = useRef<HTMLElement | null>(null);


const passFocus = () => {
    btnRef?.current?.focus();
  };

and optional chaining for btnRef in passFocus

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman