Reputation: 53
i got a error when i click on the clear cross button of a autocomplete with material ui. Here my AutoComplete:
<Autocomplete
autoComplete
fullWidth
options={esportTeams.list}
getOptionLabel={(option) => option.name ?? ""}
className={classes.formControl}
onChange={(e, value) => setFilter({ ...filter, team: value.name })}
renderInput={(params) => <TextField {...params} fullWidth label="Teams"
variant="outlined" value={filter.team ?? ""} size="small" />}
/>
When i click on the cross for clear the field i got this error : Cannot read property 'name' of null and i have test a lot of things but no one works ... Thanks !
Upvotes: 3
Views: 10219
Reputation: 41
EXPLANATION:
If you deeply think about the error, when you press the X button inside the Autocomplete component it triggers the onChange event because it changes the value to null
onChange={(e, value) => setFilter({ ...filter, team: value.name })}
Objects are complex data structures. The simplest object in JavaScript is the plain object — a collection of keys and associated values:
let myObject = {
companyName: 'Exploretale Technologies, OPC'
};
There are situations when an object cannot be created. For such cases, JavaScript provides a special value null — which indicates a missing object.
let myObject = null;
"null is a primitive value that represents the intentional absence of any object value."
That's why you're having this "TypeError: Cannot read properties of null (reading 'name')"
SOLUTION:
onChange={(e, value) =>
if(value === null) {
//Just give a value to a value to avoid null
//e.g. value = ""
}
setFilter({ ...filter, team: value.name })}
Upvotes: 4
Reputation: 2090
Your esportTeams.list should be an array of strings or numbers. It doesn't accept objects, your value is selected item in the input. So you can't look for a property on that.
I think you intended to do this;
onChange={(e, value) => setFilter({ ...filter, team: value })}
Upvotes: -1