我正在使用MUI AutoComplete和Formik,我想将其分组到类别中.如果它没有sub_accounts
,那么它不应该有标题标签.类似于这样:https://mui.com/material-ui/react-autocomplete/#grouped
CODESANDBOX ------> CLICK HERE
UI上的预期结果类似于:
-
零用金
-
现金存入银行-美国银行
- 美国银行-单一业主
- 美国银行-企业实体
-
现金
-
CIB -越南银行
- 越南银行个人
- 越南银行支票存款
零用金
, 现金存入银行-美国银行
, 现金
and CIB -越南银行
should be aligned.
现金存入银行-美国银行
and CIB -越南银行
cannot be clicked/selected - only its sub_accounts
can be selected as well as 零用金
and 现金
.
CODE
export const 现金AccountAutocomplete = ({
field,
form: { touched, errors, setFieldValue, values },
disabled,
...props
}) => {
const [inputValue, setInputValue] = useState("");
const handleChange = (_, newValue, reason) => {
if (reason === "clear") {
setFieldValue(field.name, { id: "", name: "" });
return;
}
setFieldValue(field.name, newValue);
};
const handleInputChange = (_, newInputValue) => {
setInputValue(newInputValue);
};
const extractSubAccounts = (accounts) => {
if (!Array.isArray(accounts)) {
console.error("Invalid accounts data. Expected an array.");
return [];
}
return accounts.flatMap(
({ id, name, sub_accounts }) =>
sub_accounts && sub_accounts.length > 0
? extractSubAccounts(sub_accounts) // Recursively extract sub-accounts
: [{ id, name }] // Include the account if it has no sub-accounts
);
};
const filteredData = extractSubAccounts(accounts);
return (
<Autocomplete
{...field}
disabled={disabled}
getOptionLabel={(option) =>
typeof option === "string" ? option : option?.name || ""
}
renderOption={(props, option) => {
return (
<li {...props} key={option.id}>
{option?.name}
</li>
);
}}
filterOptions={(x) => x}
options={filteredData || []}
autoComplete
includeInputInList
filterSelectedOptions
noOptionsText={"No data"}
onChange={handleChange}
inputValue={inputValue}
onInputChange={handleInputChange}
renderInput={(params) => (
<TextField
{...params}
{...props}
error={touched[field.name] && errors[field.name] ? true : false}
helperText={
touched[field.name] &&
errors[field.name] &&
String(errors[field.name].id)
}
/>
)}
fullWidth
/>
);
};