skip to Main Content

I am trying to create a custom component with react native TextInput component, and passing onChange props down to TextInput alongside some other code, but the event type is wrong according to typescript.

CustomComponent:

import type { TextInputProps } from "react-native";

interface InputProps extends InputHTMLAttributes<TextInputProps> {
  errorMsg?: string;
  labelText?: string;
  appearance?: "primary" | "rounded";
}

export default function Input(props: HTMLInputElement, InputProps) {
  return
  <TextInput
    placeholder=(props.placeholder)
    onChange={(e) => {
      setText(e.nativeEvent.text)

      if(props.onChange) props.onChange(e)
    }}
  />
}

But typescript says:

Argument of type 'NativeSyntheticEvent<TextInputChangeEventData>' is not assignable to parameter of type 'ChangeEvent<TextInputProps>'.
  Types of property 'target' are incompatible.
    Type 'Component<unknown, {}, any> & Readonly<NativeMethods>' is not assignable to type 'EventTarget & TextInputProps'.
      Type 'Component<unknown, {}, any> & Readonly<NativeMethods>' is missing the following properties from type 'EventTarget': addEventListener, dispatchEvent, removeEventListenerts(2345)
(parameter) e: NativeSyntheticEvent<TextInputChangeEventData>

Tried changing types and looking online for similar problems but no success

2

Answers


  1. I feel like this is what you’re looking for. Since TextInput is already a component, you just want to extend it’s props.

    interface InputProps extends TextInputProps {
      errorMsg?: string;
      labelText?: string;
      appearance?: "primary" | "rounded";
    }
    
    export default function Input(props: InputProps) {
      return  <TextInput placeholder={props.placeholder}
        onChange={(e) => {
    
          if(props.onChange) props.onChange(e)
        }}
      />
    }
    
    
    Login or Signup to reply.
  2. Try with onChangeText={newText => setText(newText)} instead of onChange.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search