How to set an event listener for search input change using react-select?

Viewed 2135

I have a select drop-down that has roughly 17k options, so rendering them outright isn't an option. Instead I will wait for a user to begin searching in the drop-down search bar, and once the data is reduced to a renderable size, the drop-down will show.

I can't seem to find a way to set an event handler for the search bar using react-select.

Here is the MRE:

import Select from 'react-select';

class CategoryDropdown extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      selected: '',
    }
  }

  async componentDidMount() {
    const response = await fetch('some endpoint');
    let data = await response.json();
    this.setState({
      data,
    });
  }

  handleChange(event) {
    console.log(event);
  }

  render() {
    return (
      <Select
        name="category_id",
        options={this.state.data}
        value={this.state.selected}
        onChange={this.handleChange}
        onInputChange={this.handleChange}
      />
    );
  }
}

The handleChange listener triggers when an option is selected, but not when text is entered into the search bar.

What am I missing?

1 Answers

You need to use AsyncSelect instead of Select then use the input value and callback to fetch the data that match typed input :

import React, { Component } from 'react';

import AsyncSelect from 'react-select/async';

const loadOptions =async (inputValue, callback) => {
 const response = await fetch('some endpoint');//use that input value in the endpoint
    let data = await response.json();
  callback(data)
};

export default class WithCallbacks extends Component {
  state = { inputValue: '' };
  handleInputChange = (newValue) => {
    const inputValue = newValue.replace(/\W/g, '');
    this.setState({ inputValue });
    return inputValue;
  };
  render() {
    return (
      <div>
     
        <AsyncSelect
          cacheOptions
          loadOptions={loadOptions}
          defaultOptions
          onInputChange={this.handleInputChange}
        />
      </div>
    );
  }
}

Please check this example

Related