Reputation: 405
I am trying to create onChange function in my react-select. Here is my following code:
const find = (event) => {
event.preventDefault();
if (event.target.value === "Users") {
setSearchUsers(true);
setSearchTeams(false);
} else if (event.target.value === "Teams") {
setSearchUsers(false);
setSearchTeams(true);
}
};
<Select
className="search-select"
instanceId="long-value-select"
closeMenuOnSelect={false}
components={animatedComponents}
defaultValue="Select"
isMulti
onChange={(e) => find(e.target.value)}
options={searchData}
/>
When I try to change options it's giving me this error
TypeError: event.preventDefault is not a function
How can I use onChange function in this case?
Upvotes: 8
Views: 38076
Reputation: 2181
You are passing the event.target.value
into the find
method and then using that event value to get the event.target.value
again. You do not need to do this again as you already passed the value. The prevenDefault()
method does not exist on the event's value but it exists on the event object itself. Just pass the event object as the argument to use the preventDefault()
.
onChange={(e) => find(e)}
Upvotes: 8
Reputation: 63587
This handler only passes the value of the event to find
, not the event, and the value doesn't have a preventDefault
method.
onChange={(e) => find(e.target.value)}
Pass the event to the function just using the handler...
onChange={find}
...and then have the function extract the value
function find(event) {
event.preventDefault();
const { value } = e.target;
if (value === 'Users') {
// ...
}
}
Upvotes: 2
Reputation: 2037
onChange={(e) => find(e.target.value)}
You're passing the selected value to the find function which is a value not an event therefore you get the error.
Changing it to onChange={find}
will work smoothly because the default action is cancellable.
Upvotes: 0
Reputation: 12807
Just update onChange
like this:
onChange={(e) => find(e)}
or shorter:
onChange={find}
Upvotes: 4