Home > Software engineering >  How to make search in select box using React JS?
How to make search in select box using React JS?

Time:05-12

I am making a select box with the help of enter image description here

Code: (Options from api)

  <Select mode="multiple" style={{ width: 120 }}>
    {data.map(({ label, value, text }) =>
      label ? (
        <Select.Option value={value || ""} key={label}>
          {text}
        </Select.Option>
      ) : null
    )}
  </Select>

enter image description here

Working Example:

Edit antd-select-clear (forked)

CodePudding user response:

You've mixed up the label and value values. The label is the name value that you are typing in and trying to match.

useEffect(() => {
  fetch("https://api.github.com/users")
    .then((res) => res.json())
    .then((data) => {
      const userData = data.map((item) => ({
        label: item.login, // <-- input values you are matching
        value: item.id
      }));
      setData(userData);
    });
}, []);

...

<Select mode="multiple" style={{ width: 120 }}>
  {data.map(({ label, value, text }) => (
    <Select.Option value={label} key={value}> // <-- label is option value
      {label}
    </Select.Option>
  ))}
</Select>

Edit how-to-make-search-in-select-box-using-react-js

CodePudding user response:

It works when value is as same as option text. Probably antd's peculiarity

  <Select mode="multiple" style={{ width: 120 }}>
    {data.map(({ label, value, text }) =>
      label ? (
        <Select.Option value={label} key={label}>
          {text}
        </Select.Option>
      ) : null
    )}
  </Select>
  • Related