Home > Software engineering >  Hide the value after choosing it in a live search using React
Hide the value after choosing it in a live search using React

Time:10-01

I created a live search input, and every time I press on a letter, multiple choices pop out. Also, after I choose a value, the value appears in the input field. But I want to make it so that after choosing a value, it will hide the value from the live search values.

Before choosing the value: Before choosing the value:

After choosing the value (the value stays - marked in red) After choosing the value (the value stays - marked in red)

the code:

<div>
                    <input type="text" placeholder="Choose food" onChange={(e) => setValue(e.target.value)} value={value} />
                    <div>
                        {result.map((res, index) => (
                            <a href='#' key={index} className="decoration" onClick={e => setValue(res)} >
                                <div className='box-style'>
                                    <h5 className='text-style'>
                                        {res}
                                    </h5>
                                </div>
                            </a>
                        ))}
                    </div>
                </div>

CodePudding user response:

You have to do something like this

const result = ["A", "B", "C"];

export default function App() {
  const [value, setValue] = useState("");
  const [selected, setSelected] = useState([]);

  return (
    <div>
      <input
        type="text"
        placeholder="Choose food"
        onChange={(e) => setValue(e.target.value)}
        value={value}
      />
      <div>
        {result.filter(x => x !== "" && selected.includes(x) == false).map((res, index) => (
          <a
            href="#"
            key={index}
            className="decoration"
            onClick={(e) => {
              setValue(res)
              setSelected(current => [...selected, res])
            }}
          >
            <div className="box-style">
              <h5 className="text-style">{res}</h5>
            </div>
          </a>
        ))}
      </div>
    </div>
  );
}


Evey time you select something from the menu you add it to array. then when you want to render the list (result) you filter out what in the selected array

  • Related