React/Typescript - How to handle different event types in single onChange handler function

Viewed 46

I have a form which is built up of differing types of inputs, utilising the mui library. I want to take the values of differing types of input components, and store them within a single state in a Grandparent component. I am able to handle different types of inputs if they have the same Event function structure (i.e. (e: React.ChangeEvent<HTMLInputElement>) => void), but I am now using the AutoComplete component, and since it has a different onChange event handler, I am unsure as to how I would be able to process it's change within a single onChange handler.

Please look at this codesandbox link for the rough structure of the problem. I would like the input of Child3 to be handled within the getNameAndValueFromEvent() method within valueStates.ts (which is called in Grandparent.tsx).

1 Answers

Autocomplete's onChange event is slightly different than TextField's onChange event. As a result, you cannot directly handle them by a single value change handler function.

You can add a new value change handler for Autocomplete in Child3 component to send the required parameters for valueChange function.

Your Child3 component can be like:

const Child3: React.FC<Props> = ({ id, valueChange }) => {
  const handleValueChange = (event: React.SyntheticEvent, val: string) => {
    const dataToBeSent = {
      target: {
        name: id,
        value: val
      }
    }
    valueChange(dataToBeSent, id)
  }

  return (
    <>
      <Autocomplete
        multiple
        disableCloseOnSelect
        id="tags-outlined"
        options={options}
        getOptionLabel={(option) => option.name}
        filterSelectedOptions
        onChange={handleValueChange}
        renderInput={(params) => (
          <TextField
            {...params}
            label="Child3"
            placeholder="Option"
            name={id}
          />
        )}
      />
    </>
  )
}

You can take a look at this forked sandbox for a live working example of this approach.

Related