I have a use case where I'd like the use to pick between true, false, and undefined:
const [value, setValue] = useState<boolean | undefined | null>(null)
<Autocomplete
options={[true, false, undefined]}
value={value}
renderInput={params => <TextField {...params} />}
style={{width: 150}}
getOptionLabel={value => value === undefined ? '<undefined>': `${value}`}
onChange={(event: any, newValue: boolean | undefined | null) => setValue(newValue)}
/>
This almost does exactly what I want: It renders the dropdown with the strings true, false, and <undefined>, and it correctly sets the value to either a boolean or undefined when I make a selection, and sets it to null when I clear a selection. But it refuses to display the value undefined in the text box itself; when I choose that option, I just see an empty string:
It seems that getOptionLabel for some reason does not apply the label in the textbox itself, only in the dropdown. (I know the value undefined is actually in there because it can be cleared with the clear button.)
How can I get Autocomplete to render some string (e.g. <undefined>) in the textbox when the value is undefined?
CodePudding user response:
I think you are asking in the wrong way
getOptionLabel={value => value === undefined ? '<undefined>': `${value}`}
You should ask if the type of the element is 'undefined'
getOptionLabel={value => typeof value === 'undefined' ? '<undefined>': `${value}`}
CodePudding user response:
Try to use string as value for state.
type Value = 'true' | 'false' | 'undefined';
const [value, setValue] = useState<Value | null>(null);


