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?
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)}
Just update onChange like this:
onChange={(e) => find(e)}
or shorter:
onChange={find}
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') {
// ...
}
}