I'm trying to create a custom Select component that uses material ui's Autocomplete as a base.
However, I'm running into issues trying to set the value to a string like how normal select dropdowns are usually used. It seems to only work if I set the value to the whole object.
App.js
const options = [
{ id: '1', name: 'United States' },
{ id: '2', name: 'Canada' },
{ id: '3', name: 'Mexico' },
];
const App = () => {
const [val, setVal] = useState();
return (
<Select
options={options}
value={val} //<----- only works if val === one of the country objects in options array, but i want to se it as country.id
label="Country"
placeholder="Enter a country"
onChange={newValue => setVal(newValue)}
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
/>
);
}
Select.js:
const Select = ({
getOptionLabel,
getOptionValue,
placeholder,
options,
label,
onChange,
value = ""
}) => {
const compareOptionAndValue = (option, value) => {
console.log("oooooooooo", option);
console.log("vvvvvvvvvvv", value);
console.log("eeeeeeee", getOptionValue(option) === value);
return getOptionValue(option) === value;
};
return (
<MuiAutocomplete
options={options}
value={value}
getOptionSelected={compareOptionAndValue}
getOptionLabel={(option) =>
option && getOptionLabel(option) ? getOptionLabel(option) : ""
}
onChange={(_event, option) => onChange(getOptionValue(option))}
renderInput={(params) => (
<MuiTextField
{...params}
label={label}
placeholder={value ? undefined : placeholder}
variant="outlined"
fullWidth
/>
)}
/>
);
};
getOptionSelected doesn't work as expected. I thought it would help determine which option was selected but it doesn't do anything even though it returns true.
Here's a codesandbox example:
https://codesandbox.io/s/material-ui-autocomplete-forked-brjis?file=/src/index.js