Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 843
Dan Avatar asked Jun 01 '26 05:06

Dan


1 Answers

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.

like image 114
Erick Willian Avatar answered Jun 02 '26 17:06

Erick Willian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!