I was going through Mui Documentation, in the Autocomplete
component section I got two props
,getOptionLabel
and getOptionSelected
which I got the definition but I did not understand it properly. So it will great if anyone can give me the proper definition in a simple way with example
getOptionLabel
is use to show the text in the dropdown
EX: autocomplete array
const top100Films = [
{ title: 'The Shawshank Redemption', year: 1994 },
{ title: 'The Godfather', year: 1972 },
{ title: 'The Godfather: Part II', year: 1974 },
{ title: 'The Dark Knight', year: 2008 }
}
<Autocomplete
id="combo-box-demo"
options={top100Films}
getOptionLabel={(option) => option.year.toString()} // in the dropdown the option text will be year,if we use like option.title then it will show the title of the movie in dropdown
......
getOptionSelected
this is use to determine the selected value of given array
<Autocomplete
id="combo-box-demo"
options={top100Films}
getOptionSelected={(option) => option.year === 1994}
....
//this will select all the option which has year as 1994 and make the background of that option darker
demo
getOptionLabel
Like Kalhan said, getOptionLabel sets the string label in the dropdown.
For example:
const users = [
{ userName: 'bob', age: 20, message:[...] },
{ userName: 'jane', age: 43, message:[...] },
{ userName: 'joe', age: 88, message:[...] },
}
<Autocomplete
id="combo-box-demo"
options={users}
getOptionLabel={(user) => user.userName }
To clarify, getOptionSelected is used to determine if the selected value (i.e. the string in the autocomplete text field when you select an item from the dropdown) matches an option (in this case, user object) from the options array.
According to the Material-ui docs, getOptionSelected
has the following signature, where option is the option to test and value is the value to test against:
function(option: T, value: T) => boolean
As an example, by using getOptionSelected, I can get the full user object when an element is selected from the dropdown (also avoids warnings such as, "The value provided to Autocomplete is invalid...")
const users = [
{ userName: 'bob', age: 20, message:[...] },
{ userName: 'jane', age: 43, message:[...] },
{ userName: 'joe', age: 88, message:[...] },
}
<Autocomplete
id="combo-box-demo"
options={users}
getOptionLabel={(user) => user.userName }
getOptionSelected={(option, value) => option.userName === value.userName }
onChange={(event, newValue) => {
this.setValue(newValue);
}}
// more code
setValue = (newValue) => {
console.log(newValue); // { userName: 'jane', age: 43, message:[...] }
}
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