I am trying to replicate the autocomplete MUI example here. But instead of using a JSON data structure, I am just passing an Array.
I am trying the following:
export default function SearchTutorialArray() {
const top100Films = [
'The Shawshank Redemption',
'The Godfather',
'The Godfather: Part II',
'The Dark Knight',
'12 Angry Men',
"Schindler's List",
'Pulp Fiction',
'The Lord of the Rings: The Return of the King',
'The Good, the Bad and the Ugly'
];
const options = top100Films.map((option) => {
const firstLetter = option[0].toUpperCase();
return {
firstLetter: /[0-9]/.test(firstLetter) ? '0-9' : firstLetter,
...option,
};
});
return (
<Autocomplete
id="grouped-demo"
options={options.sort((a, b) => -b.firstLetter.localeCompare(a.firstLetter))}
groupBy={(option) => option.firstLetter}
getOptionLabel={(option) => option}
sx={{width: 300}}
renderInput={(params) => <TextField {...params} label="With categories"/>}
/>
);}
I think the main issue is in the line getOptionLabel={(option) => option} which makes the function to return this error:
Objects are not valid as a React child (found: object with keys {0, 1,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, firstLetter}). If you meant to render a
collection of children, use an array instead.
When changing this line to getOptionLabel={(option) => option[0]} the dropdown is working correctly, but only showing the first letter for every film.
>Solution :
You can use the following appraoch:
const options = top100Films.map((option) => {
const firstLetter = option[0].toUpperCase();
return {
firstLetter: /[0-9]/.test(firstLetter) ? '0-9' : firstLetter,
// no spreading ... here
label: option,
};
});
later:
<Autocomplete
id="grouped-demo"
options={options.sort((a, b) => -b.firstLetter.localeCompare(a.firstLetter))}
groupBy={(option) => option.firstLetter}
// read from label attribute
getOptionLabel={(option) => option.label}
sx={{width: 300}}
renderInput={(params) => <TextField {...params} label="With categories"/>}
/>