n4kz / react-native-material-textfield

Material textfield
Other
901 stars 831 forks source link

Ref doesn't support useRef hook in TypeScript #311

Closed bezenson closed 2 years ago

bezenson commented 3 years ago

Code example:

const fieldRef= useRef<FilledTextField>();
return <TextField ref={fieldRef}  />

Gotten error:

No overload matches this call.
  Overload 1 of 2, '(props: Pick<Pick<TextFieldProps & RefAttributes<FilledTextField> & { inputContainerStyle: StyleProp<ViewStyle>; ... 5 more ...; labelOffset: { ...; }; }, "defaultValue" | ... 132 more ... | "key"> & Partial<...>, "defaultValue" | ... 139 more ... | "labelOffset"> & { ...; } & { ...; } & { ...; }): ReactElement<...>', gave the following error.
    Type 'MutableRefObject<FilledTextField | undefined>' is not assignable to type '((instance: FilledTextField | null) => void) | RefObject<FilledTextField> | null | undefined'.
      Type 'MutableRefObject<FilledTextField | undefined>' is not assignable to type 'RefObject<FilledTextField>'.
        Types of property 'current' are incompatible.
          Type 'FilledTextField | undefined' is not assignable to type 'FilledTextField | null'.
            Type 'undefined' is not assignable to type 'FilledTextField | null'.
  Overload 2 of 2, '(props: StyledComponentPropsWithAs<typeof FilledTextField, DefaultTheme, { inputContainerStyle: StyleProp<ViewStyle>; tintColor: string; activeLineWidth: number; disabledLineWidth: number; fontSize: number; lineWidth: number; labelOffset: { ...; }; }, "fontSize" | ... 5 more ... | "labelOffset">): ReactElement<...>', gave the following error.
    Type 'MutableRefObject<FilledTextField | undefined>' is not assignable to type '((instance: FilledTextField | null) => void) | RefObject<FilledTextField> | null | undefined'.
      Type 'MutableRefObject<FilledTextField | undefined>' is not assignable to type 'RefObject<FilledTextField>'.ts(2769)

I think just TypeScript file should be fix because everything seems to be working

SamiChab commented 3 years ago

Try this:


import { TextField } from 'react-native-material-textfield'

const textInputRef = useRef<TextField>(null)

<TextField
    ref={textInputRef}
    {...} // other props
/>

Then use textInputRef.current.setValue('Hello world') or textInputRef.current.focus()