htmlreactjstypescriptinputhtml-datalist

How to make input box show the options that match with the beginning of the user's input using html datalist?


I am new to React and want to implement an autocomplete suggestion box for a text input box that matches only the first letters of the options available and not just any substring which is the current behaviour of HTML's <datalist>.

I have found great answers in jQuery achieving exactly the behaviour that I need. I am just having a hard time finding a way I can achieve this behaviour using React syntax.

Here are the jQuery solutions I have found so far.

How to make datalist match result from beginning only

HTML5 Datalist auto suggest shows the list that starts with the search keyword

Here is my current code structure:

<div className="form-field word-field">
      <label>Word</label>
      <Field list="word_list" id="word" name="word" />
       {errors.word && touched.word && <div className="validation-error">{errors.word}</div>}
      <datalist id="word_list">
         <option>Arc</option>
         <option>House</option>
         <option>Handle</option>
         <option>Chair</option>
         <option>Door</option>
      </datalist>
</div>

Can I be given any pointers on how to achieve this? What should I look into to get the behaviour I need?

Thanks!


Solution

  • I have developed a simple component that does this with datalist:

    import { useState } from "react";
    
    const initialOptionsArr = [
      "India",
      "United States",
      "United Kingdom",
      "Germany",
      "France",
      "Israel"
    ];
    export default function App() {
      const [options, setOptions] = useState(initialOptionsArr);
    
      const handleInputChange = ({ target }) => {
        if (target.value) {
          const filteredOptions = initialOptionsArr.filter((option) =>
            option.toLowerCase().startsWith(target.value.toLowerCase())
          );
          setOptions(filteredOptions);
        } else {
          setOptions(initialOptionsArr);
        }
      };
    
      return (
        <div>
          <input
            type="text"
            list="countries"
            name="mycountry"
            id="countryInput"
            onChange={handleInputChange}
          />
          <datalist id="countries">
            {options.map((item) => (
              <option value={item}>{item}</option>
            ))}
          </datalist>
        </div>
      );
    }
    

    This code uses useState hook and is pretty simple. Please let me know if this helps you. Here is a sandbox link of above: https://codesandbox.io/s/funny-hodgkin-7lsu5v?file=/src/App.js