0

I'm trying to make a search bar and suggestions list, when a suggestion is clicked the value of the input box should change to the value of the suggestion element and that happens indeed. input box have an onChange event which fires a handleChange function. That works and the onChange event usually get fired. But when the input changes due to clicking a suggestion the onChange function doesn't get fired

Here is the code

import "./App.css";
import React, { useState, useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {

  var [searchTerm, setSearchTerm] = useState("");

function handleSearchTerm(event) {
    const newValue = event.target.value;
    setSearchTerm(event.target.value); //the rest of the function};

const changeInput = (event) => { //the function that is supposed to get fired
    setSearchTerm(event);
  };
return(
    <div className="App">
      <input
        type="text"
        value={searchTerm}
        onChange={handleSearchTerm}
        className="input"
      ></input>
      <div className="dropdown">
        {filteredList  //the array that handles the search
          .filter((item) => {
            const value = searchTerm.toLowerCase();
            const fullName = item.title.toLowerCase();

            return value && fullName.startsWith(value) && fullName !== value;
          })
          .slice(0, 10)
          .map((item) => (
            <div
              onClick={() => changeInput(item.title)}
              className="dropdown-row"
              key={item.title}
            >
              {item.title}
            </div>
          ))}

      </div>
    </div>

)
}
  • 1
    "onChange event usually get fired except for when the suggestion is clicked". I don't understand why you expect a click event to fire an onChange. – jmargolisvt Sep 29 '22 at 14:21
  • @jmargolisvt I have edited the question and now it's clearer you can read it again please – AbdelrahmanAhmed Sep 29 '22 at 14:23
  • @jmargolisvt the onChange function get fired when I manually change the text box but when the input changes due to the suggestion click it doesn't get fired, maybe that's because the value itself changes and no input is being made but I can't solve the problem – AbdelrahmanAhmed Sep 29 '22 at 14:24
  • Does this answer your question? [React: trigger onChange if input value is changing by state?](https://stackoverflow.com/questions/42550341/react-trigger-onchange-if-input-value-is-changing-by-state). This is essentially the same issue, exept this question uses state. – jmargolisvt Sep 29 '22 at 14:27
  • @jmargolisvt It does answer my question but unfortunately I can't understand the solution as I'm new in react and I only work with functional components , can you help me with the solution please? – AbdelrahmanAhmed Sep 29 '22 at 14:37
  • @jmargolisvt ماترد يبن العرص – AbdelrahmanAhmed Sep 29 '22 at 15:21

0 Answers0