Dan
Dan

Reputation: 295

ReactJS autocomplete from React Bootstrap not working

I'm trying to build an autocomplete search field, using this form component from React Bootstrap, which is rendered as a input by the browser.

Here's what I did in my React component:

<FormControl
 id="frenchToEnglishInput"
 placeholder="type a word..."
 aria-label="Recipient's username"
 autocomplete="on"
 data={frenchToEnglishWords}
 onChange={this.fetchFrenchToEnglish}
 renderItem = {item => {
   return (
     <div>
       {item}
     </div>
   );
 }}
/>

the frenchToEnglishWords array is declared outside the component as a var, as I intend to update it as I type some value into the input field.

Now here is the function that triggers the onChange event :

fetchFrenchToEnglish = async () => {
    if(document.getElementById("frenchToEnglishInput").value!==''){

      axios.get(dictionaryURIs.english.French_English+""+document.getElementById("frenchToEnglishInput").value)
      .then(response => {
          frenchToEnglishWords = response.data
      })

    }
  }

The request is made from MongoDb, after setting up an autocomplete index on a collection, but this part works fine.

My question is, why is the only "autocomplete" I'm getting is the one made of the previous words I've typed ?

input wrong autocomplete

Or maybe the array I'm using as input data must be a const (as I've seen in many examples) and not a var ? When I do type in some word, I do not get any autosuggestion from the frenchToEnglishWords, which is being updated from the DB.

Upvotes: 9

Views: 7784

Answers (1)

Erick Willian
Erick Willian

Reputation: 4369

You need to use State!

This is not working because the data field is not a State, you need to bind the fetchFrenchToEnglish function to the data state.

But first of all, there's no reason to use var, because the most differences between them is just scope and immutability, here is more about it.

Also, you can use hooks like useState and useRef to no use getElementById.

Upvotes: 1

Related Questions