I have an object:
company: {
name: 'Google',
id: '123asd890jio345mcn',
}
I need to print its name as an option of material-ui selector (Autocomplete rendering TextField)
But when user clicks on it, i need to return it's ID to an State or something else, so I can use it later.
return (
<Autocomplete
id="company"
open={open}
onOpen={() => {
setOpen(true);
}}
onClose={() => {
setOpen(false);
}}
loadingText="Buscando empresas..."
isOptionEqualToValue={(option, value) => option.id === value.id}
getOptionLabel={(option) => option.id}
renderOption={(props, option) => (
<Box component="li" {...props}>
{option.name}
</Box>
)}
options={options}
loading={loading}
noOptionsText="Nenhuma empresa cadastrada"
defaultValue={data.company}
renderInput={(params) => (
<TextField
{...register("company")}
{...params}
label="Empresa"
placeholder="Selecione a empresa"
InputProps={{
...params.InputProps,
endAdornment: (
<React.Fragment>
{loading ? (
<CircularProgress color="inherit" size={20} />
) : null}
{params.InputProps.endAdornment}
</React.Fragment>
),
}}
/>
)}
/>
);
}
I've tried a lot. But the only argument I can retrieve from this Autocomplete is it's current value, which is ID OR name. I can't show the name and retrieve the ID.
Is it possible?
CodePudding user response:
Have you tried using onChange
? You can get the entire object from onChange second argument, value. I've made a simplified version here: https://codesandbox.io/s/react-repl-forked-nqv8pw?file=/src/index.js:464-504
<Autocomplete
// your other props
getOptionLabel={(option) => option.name}
onChange={(_, value) => console.log(value)}
// your other props
/>