Home > database >  what kind of event type is the event on the onInputChange props?
what kind of event type is the event on the onInputChange props?

Time:12-13

I am trying to use React.ChangeEvent on the mui v4 autocomplete component since I don't want to go with any. how ever it is throwing an error that the current event is not compatible.

  const handle = (e: React.ChangeEvent<HTMLTextAreaElement>, currentValue: string, reason: string) => {
  console.log(e,currentValue,reason)
  }

<Autocomplete onInputChange={handle}/>

CodePudding user response:

You can use TypeScript's inference capabilities along with some type utilities to derive the function signature that you're asking about.

Here's an example using a type annotation on a handler function:

TS Playground

import { type ChangeEvent } from 'react';
import {
  Autocomplete,
  type AutocompleteInputChangeReason,
     //^? (alias) type AutocompleteInputChangeReason = "input" | "reset" | "clear"
} from '@material-ui/lab';

type OnInputChange = Parameters<typeof Autocomplete>[0]['onInputChange'];

const handleInputChange: OnInputChange = (event, value, reason) => {
  event;
//^? (parameter) event: ChangeEvent<{}>

  value;
//^? (parameter) value: string

  reason;
//^? (parameter) reason: AutocompleteInputChangeReason

  // Your implementation here
};

Note that the Autocomplete component function is generic, but — in my testing — no variation in supplied generic types seems to affect the generic type used for the inner ChangeEvent parameter, and the result is always ChangeEvent<{}>.

The type for ChangeEvent (which comes from React) is ChangeEvent<T = Element>, so if you are targeting a specific element, you can use the information above to write your own compatible function signature manually, but using the specific element type that is most appropriate for your scenario.

CodePudding user response:

Signature:

function(event: object, value: string, reason: string) => void
event: The event source of the callback.
value: The new value of the text input.
reason: Can be: "input" (user input), "reset" (programmatic change), "clear".

MUI documentation for Autocomplete API

  • Related