skip to Main Content

I have a react-select component, I want to add a functionality such that as soon as somebody types something in the react-select, There should be a api request that would fetch the items related to that keyword entered, How can i do this

2

Answers


  1. Well You can do this without any API call just use the filter method to filter your options

    Login or Signup to reply.
  2. You should try looking into AsyncSelect from ‘react-select/async’
    Then create a function in your component to load the options from your API which should accept an input string and a callback and should make the API call based on the input string. Something 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 in your componen pass your loadOptions function into the loadOptions prop

    const YourComponent = () => {
        return (
           <AsyncSelect
             cacheOptions
             defaultOptions
             loadOptions={loadOptions}
           />
        );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search