8

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?

0

4 Answers 4

8

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)}
Sign up to request clarification or add additional context in comments.

1 Comment

onChange={find} will automatically pass the event to function.
4

Just update onChange like this:

onChange={(e) => find(e)}

or shorter:

onChange={find}

4 Comments

still getting the error TypeError: event.preventDefault is not a function
What are you using preventDefault for? Is it to stop a form from submitting?
onChange in react-select return a value not an event so you cannot use event.preventDefault
I see. Thanks for pointed out the mistake for me. So how do I change my onChange function to make it work with react-select? When I selected an option and I console.log(value) it's giving me this 0: label: "Users", value: "Users"
2

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') {
    // ...
  }
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.