Today I come to you with a question that has been bugging me this past few days or so.
I am trying to make it so my autocomplete shows a label in the option, but the value is different. And so I googled around and found out you can do it with renderOption. So I tried renderOption and I can't get it to work at all, and it's throwing me a error that I do not understand.
My code below:
const itemList = [
{ value: "Car Winner", id: "casinofob" },
{ value: "PD 556", id: "-2084633992" },
{ value: "Cluckin Drink", id: "cbdrink" },
{ value: "Blink", id: "spellbook-blink" },
];
<Autocomplete
disablePortal
id="combo-box-demo"
options={itemList}
renderOption={option => <>{option.value}</>}
getOptionLabel={(option) => option.id}
sx={{ width: 300 }}
renderInput={(params) => <TextField onChange={updateSpawnEnteredItem} label="Item Name" sx={{marginBottom: '15px', marginTop:'5px', width: 300 }} {...params} />}
/>
The error I am getting is as follows: "Property 'value' does not exist on type 'HTMLAttributes'
If anyone can help me solve this error, I'd be eternally grateful since I've had this problem for days now.
Regards.
You need to pass the props along and return an li element.
Here is a more complex example where option has two properties:
interface AcOption {code: string, description: string}
<Autocomplete
multiple
id="ac-field-id"
autoComplete={true}
options={acOptions || []}
loading={acOptionsLoading}
filterSelectedOptions={true}
groupBy={(option) => option?.code?.[0] || ''}
isOptionEqualToValue={(option: AcOption, value: AcOption) => option.code === value.code}
onInputChange={(event, newInputValue) => {
setInputAcOption(newInputValue)
}}
onChange={handleAcOptionChange}
value={state.acOptions || []}
filterOptions={(x) => x}
getOptionLabel={(option: AcOption) => option?.code || ''}
renderOption={({ key, ...props }, option: AcOption) => (
<li key={key} {...props}>{option.code} {option.description}</li>
)}
renderInput={(params) => (
<TextField {...params} label="AC Option" />
)}
/>
EDIT: the key property as part of the spread will trigger an error (React). This is avoided by explicitly setting the key prop.
you need to pass props
renderOption={(props: object, option: any, state: object) => (
<div className={styles.option} {...props}>
{option.name}
</div>
)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With