Currently I am working on a search bar component which will be integrated with an api which will return results which might have an nested option. The problem is MUI autocomplete doesn’t support nested options by default. I tried some work arounds and the best I could come with is something like this
const Page = () => {
const [value, setValue] = useState("");
return (
<Container sx={{ height: 428, backgroundColor: "#C5E8EF" }}>
<Typography fontSize={40}>Movies</Typography>
<DrugSearchBar
freeSolo
options={top100Films}
filterOptions={(options) => options}
renderInput={(params) => {
return (
<TextField
{...params}
sx={{ fontFamily: FONTS.SOURCE_SANS_PRO, fontWeight: 400 }}
placeholder="Search Movies"
value={value}
onChange={(event) => setValue(event.target.value)}
InputProps={{
...params.InputProps,
startAdornment: (
<SearchIcon
sx={{
color: colors["--primary-teal"],
height: 32,
width: 32,
}}
/>
),
}}
/>
);
}}
renderOption={(props, option) => <SearchList {...props} option={option} key={option.label}/>}
/>
</Container>
);
};
export default Page;
const SearchList = (props) => {
const [open, setOpen] = useState(true);
const { option, ...optionProps } = props;
return (
<>
{option.sublist ? (
<>
<ListItem
{...optionProps}
onClick={() => setOpen((prev) => !prev)}
>
{option.label}
</ListItem>
<Collapse in={open} timeout="auto" >
{option.sublist.map(item => (
<List component="div" disablePadding >
<ListItem sx={{ pl: 4 }} key={item.label} >
{item.label}
</ListItem>
</List>
))}
</Collapse>
</>
) : (
<ListItem {...optionProps}>
{option.label}
</ListItem>
)}
</>
)
}
The problem with the above approach is I am unable to selected the nested option using click or keyboard arrow buttons. I want the sub list items to be clickable and also automatically collapse/open when clicking them.
Demo api response:
onst top100Films = [
{
label: "Harry Potter",
sublist: [
{ label: "Philosopher's Stone", year: 1979 },
{ label: "Deathly Hollows", year: 1950 },
],
},
{ label: "The Shawshank Redemption", year: 1994 },
{ label: "The Godfather", year: 1972 },
{ label: "The Godfather: Part II", year: 1974 },
{ label: "The Dark Knight", year: 2008 }
]
enter image description here
Dharaneeswaran R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.