javascriptreactjsantdmulti-select

How to make search in select box using React JS?


I am making a select box with the help of Antd design.

Current scenario:

-> I am making two select box here, in which one select has static data and another from api.

Issue:

-> While I type keyword to select options, static one works but the dynamic options (data from api) doesn't works and display the No data text.

Expectation:

Both the static and dynamic select box needs to display the options as per the search keyword in the select box.

Code: (Options as static)

  <Select mode="multiple" style={{ width: 120 }}>
    <Select.Option value="jack">Jack</Select.Option>
    <Select.Option value="lucy">Lucy</Select.Option>
    <Select.Option value="disabled" disabled>
      Disabled
    </Select.Option>
    <Select.Option value="Yiminghe">yiminghe</Select.Option>
  </Select>

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)


Solution

  • 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