search

Home  >  Q&A  >  body text

Want to get options on inputValue change in react select

I have a react-select component and I want to add a functionality so that once someone enters something in react-select there should be an api request to get the items related to the entered keyword, how can I this way

P粉775723722P粉775723722472 days ago457

reply all(2)I'll reply

  • P粉354602955

    P粉3546029552023-09-15 09:55:36

    You can do this without any API calls, just use the filter method to filter your options

    reply
    0
  • P粉675258598

    P粉6752585982023-09-15 09:32:58

    You should try to view AsyncSelect from "react-select/async" Then create a function in the component to load the options from the API, the function should accept an input string and a callback and should make an API call based on the input string. Things like this

    const loadOptions = (inputValue, callback) => {
        // api call here
        fetch('your-api-url?${inputValue}')
          .then(response => response.json())
          .then(data => {
             // do your work here
             const options = //transform data here
             callback(options)
          });
    };

    Then pass the loadOptions function into the loadOptions property in your component

    const YourComponent = () => {
        return (
           <AsyncSelect
             cacheOptions
             defaultOptions
             loadOptions={loadOptions}
           />
        );
    };

    reply
    0
  • Cancelreply