简体   繁体   中英

Recactjs autocomplete component gives error

I am new at Reactjs. I am trying to reuse this kind of ready autocomplete select component in my app as well as in the given link it gives this error for anything this not found in the input box. To see the error just type xyz and press enter and check error in the console:-

Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info:

After searching this error I found that when any uninitialized state changes it throws this warning. But in this code, I can see all states are initialized. I don't understand why is it happening? Anyway, I am new to React so I must miss something. Please let me know how to fix this error.

It's because inside the first conditional of the onKeyDown handler it's setting the state for userInput doing:

filteredSuggestions[activeSuggestion]

However, if no suggested matches are made, the array filteredSuggestions will be empty and activeSuggestion will be 0 which will result in an undefined value for userInput .

It's like saying:

 const mySuggestions = []; let choice = 0; console.log(mySuggestions[choice]); // undefined

Controlled components should always have a value, undefined is not a value. That's why React is complaining.

One way to fix this, is by using short-circuit evaluation for the value of the element:

<input
  type="text"
  onChange={onChange}
  onKeyDown={onKeyDown}
  value={userInput || ""}
/>

This basically translates to:

"If userInput is something, use whatever value it has, otherwise use an empty string".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM