React Material UI Autocomplete - how to display text name as select but send ID as a value?

Viewed 959

MATERUAL UI Autocomplete component works fine, but I want to get object.id as onSelect event value (event.target.value), not the object.name. In other words, I want to display object.name as select item labels, but I want to get object.id as onSelect event value (event.target.value). Right now, my event.target.value is the same as select item label (object.name). Here is an example (from the Material UI documentation):

The options object is like this:

const options = [
  { id: "01", name: "Peter" },
  { id: "02", name: "Mary },
  { id: "03", name: "John" }
]

And the Autocomplete is the same like in Material UI documentation:

<Autocomplete
      id="asynchronous-demo"
      fullWidth
      open={open}
      onOpen={() => {
        setOpen(true)
      }}
      onClose={() => {
        setOpen(false)
      }}
      getOptionLabel={(option) => option.name}
      options={options}
      loading={loading}
      renderInput={(params) => (
        <TextField
          {...params}
          label="Asynchronous"
          variant="outlined"
          onChange={(event) => {
            if (event.target.value !== '' || event.target.value !== null) {
              onChangeHandle(event.target.value)
            }
          }}
          onSelect={(event) => {
            onSelectHandle(event)
          }}
          InputProps={{
            ...params.InputProps,
            endAdornment: (
              <React.Fragment>
                {loading ? (
                  <CircularProgress color="inherit" size={20} />
                ) : null}
                {params.InputProps.endAdornment}
              </React.Fragment>
            ),
          }}
        />
      )}
    />

With onSelect I always get object.name as event.target.value, but I want to return object.id as event.target.value.

Does anybody knows how??

1 Answers

You are currently grabbing the value from TextField's onSelect, instead of Autocomplete's onChange.

<Autocomplete
    ...
    onChange={(event, newValue) => {
        onSelectHandle(newValue)
    }}
    renderInput={(params) => (
        <TextField
            {...params}
            label="Asynchronous"
            variant="outlined"
            onChange={(event) => {
                if (event.target.value !== '' || event.target.value !== null) {
                    onChangeHandle(event.target.value)
                }
            }}
            ...
        />
    )}
/>

For more info, check out the controllable states section in the Autocomplete documentation.

Related