datalist tag not listening to any event react js

Viewed 23

I am trying to listen to event on select or any selection of options but cannot fire any event in datalist

const handleSelect = () => {
console.log("selected");
};

let renderOptions = () => {
return filteredOptions.map((option, index) => {
  return (
    <option key={index} value={option.value}>
      {option.option}
    </option>
  );
});
};


return (
<div>
  <input type="text" name="example" list="exampleList" />
  <datalist onChange={handleSelect} onSelect={handleSelect} id="exampleList">
    {renderOptions()}
  </datalist>
</div>
);
1 Answers

You need to listen to onChange event of the corresponding input tag in order to listen to event on selection like this.

const filteredOptions = [
  { value: "Edge", option: "Edge" },
  { value: "Chrome", option: "Chrome" },
  { value: "Firefox", option: "Firefox" }
];

export default function App() {
  const handleSelect = (e) => {
    console.log("selected " + e.target.value);
  };

  let renderOptions = () => {
    return filteredOptions.map((option, index) => {
      return (
        <option key={index} value={option.value}>
          {option.option}
        </option>
      );
    });
  };

  return (
    <div>
      <input
        type="text"
        name="example"
        list="exampleList"
        onChange={handleSelect}
      />
      <datalist id="exampleList">{renderOptions()}</datalist>
    </div>
  );
}

You can take a look at this sandbox for a live working example of this approach.

Related