ricardolima
ricardolima

Reputation: 53

Force react-select to show all options using Elasticsearch

I'm trying to implement this with elasticsearch and it is working But how i can force this show results which can be different from the searched terms? For example i search ardino, The elasticsearch give me the word arduino but then react-select does not show that result because ardino does not contain arduino. I know the idea of this library is exactly that and it is working ok, but i have most of the things already implemented and it is only missing that part.

The handle is giving the right behavior and it is populating the options correctly.

Thank you

<Select
  name= {this.state.selectedOption}
  value={this.state.selectedOption}
  isSearchable={true}
  onChange = {(val) => {

    this._handleSearch(val.value)
  }}
  onInputChange = {(val) => {

    this._handleSearch(val)
  }}
  options={this.state.options}
/>

Upvotes: 1

Views: 1125

Answers (1)

Avi Kaminetzky
Avi Kaminetzky

Reputation: 1538

I would recommend using the Async component which can simplify your code. You will not need the onChange handler anymore.

isSearcheable is true by default, no need to specify.

In answer to your question: Make sure you are passing in label and value keys with each result option. If you want to customize any of the results, for example adding the search term in the results, you can manually manipulate the options array.

import React, {Component} from 'react';
import AsyncSelect from 'react-select/lib/Async';

class Search extends Component {

    state = {inputValue: ""}

    onInputChange = (inputValue) => {
        this.setState({ inputValue });
    };

    getSearchResults = async (inputValue) => {
        // elastic search results
        let options = await fetch(`searchElastic/${inputValue}`);

        // input value of drop-down
        const inputValue = this.state.inputValue;

        // manually add input field as an option in drop-down
        if (inputValue.length > 0)
            options.unshift({label: inputValue, value: inputValue})

        // async handling of new props
        return options.map(opt => {
            return {label: opt.name, value: opt.value}
        })
    }

    render() {
        return <AsyncSelect
            onInputChange={this.onInputChange}
            loadOptions={this.getSearchResults}
        />
    }
}

export default Search;

Upvotes: 2

Related Questions