I am trying hard to customize option elements in autocomplete list. I want to do this by use of renderOptions prop, where i can create DOM elements. Then, i can pretty easly add styles with sx or styled components.
But something is wrong. When i try to render options list elements wrapped in divs, the names of the movies are hidden (?) They are rendered, because i can still choose option, and after that it is showned as selected, but the input list is still broken, and CSS styles are not applied.
What I am missing ? Autocomplete and its styling is new for me.
The code:
<Autocomplete
freeSolo
id="free-solo-2-demo"
disableClearable
options={top100Films.map((option) => option.title)}
renderOption={(props, option) => {
return (
<li {...props}>
<div
sx={{
backgroundColor: "red",
color: "orange"
}}
>
{option.title}
</div>
</li>
);
}}
renderInput={(params) => (
<TextField
{...params}
label="Search input"
InputProps={{
...params.InputProps,
type: "search"
}}
/>
)}
/>
</Stack>
);
}
Heres the demo : https://codesandbox.io/s/freesolo-material-demo-forked-dupxol?file=/demo.js
CodePudding user response:
TL;DR Just change option.title
to option
in renderOption
prop. And use Box
instead of div
to apply styles.
I couldn't find it stated in documentation explicitly but apparently each of the elements passed to options
are then passed to renderOption
as option
argument.
So since you already pass array of option.title
strings to options
you will need to refer to them just as option
in renderOption
prop.
The sx
prop is used by MUI components. So please change div
to MUI Box
component inside renderOption
. The Box
was created specifically for such cases.