Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of highlighted option in React-Select

I'm using react-select v2 with an async select component.

        <AsyncSelect
            cacheOptions
            components={{ Option }}
            loadOptions={this.getSearchItems}
            onInputChange={this.handleInputChange}
            placeholder="Search..."
            onKeyDown={this._handleKeyPress}
        />

How do I access the value of an option that is highlighted as a result of using the down key on keyboard or hovering with a mouse?

I would like to trigger a redirect or setState based on the highlighted option. onKeyDown only sends in the input value as event.target.value.

Here is an example from Nordstrom's website:

enter image description here

like image 483
Avi Kaminetzky Avatar asked Aug 02 '18 19:08

Avi Kaminetzky


People also ask

How do you get selected value from dropdown in React-select?

How do you display a selected value in a drop down list? STEP 1 − Create a select tag with multiple options and assign an id to the select tag. STEP 2 − Also, create an empty DOM with an id to display the output. STEP 3 − Let there be a button element for the user to click and see the option selected.

How do you get the selected option ID in React?

You can add an onChange event handler to the select which checks for the selected index and retrieve the id from the selected option. This is a bit of an anti-pattern for React.

How do you use the select element in React?

How to use HTML <select> tag in ReactJS ? HTML <select> tag is used to create a drop down list with multiple options. The <select> tag is used as outer element and the <option> element is nested within <select> tag for defining options in a list.

How do I validate a dropdown in React?

const options = [ { value: 'active', label: 'Active' }, { value: 'inactive', label: 'In Active' }, { value: 'deleted', label: 'Delete' }, ]; <Select defaultValue={options[0]} isSearchable={false} className="react-dropdown" onChange={statusDropdownHandleChange} classNamePrefix="dropdown" options={options} name="status" ...


2 Answers

I don't think it's possible to do it using only react-select api, but you can create own HOC which will add this functionality to AsyncSelect.

class MyAsyncSelect extends React.Component {

  /* Select component reference can be used to get currently focused option */
  getFocusedOption() {
    return this.ref.select.select.state.focusedOption;
  }

  /* we'll store lastFocusedOption as instance variable (no reason to use state) */
  componentDidMount() {
    this.lastFocusedOption = this.getFocusedOption();
  }

  /* Select component reference can be used to check if menu is opened */
  isMenuOpen() {
    return this.ref.select.state.menuIsOpen;
  }

  /* This function will be called after each user interaction (click, keydown, mousemove).
     If menu is opened and focused value has been changed we will call onFocusedOptionChanged 
     function passed to this component using props. We do it asynchronously because onKeyDown
     event is fired before the focused option has been changed.
  */
  onUserInteracted = () => {
    Promise.resolve().then(() => {
      const focusedOption = this.getFocusedOption();
      if (this.isMenuOpen() && this.lastFocusedOption !== focusedOption) {
        this.lastFocusedOption = focusedOption;
        this.props.onFocusedOptionChanged(focusedOption);
      }
    });
  }

  /* in render we're setting onUserInteracted method as callback to different user interactions */
  render () {
    return (
      <div onMouseMove={this.onUserInteracted} onClick={this.onUserInteracted}> 
        <AsyncSelect 
          {...this.props} 
          ref={ref => this.ref = ref}
          onKeyDown={this.onUserInteracted}
        />
      </div>
    );
  }
}

Then you can use this custom component in the same way as AsyncSelect but with ability to react on focused option changes:

class App extends React.Component {

  onFocusedOptionChanged = focusedValue => console.log(focusedValue) 

  render() {
    return (
      <div>
        <MyAsyncSelect
          cacheOptions
          loadOptions={loadOptions}
          defaultOptions
          onInputChange={this.handleInputChange}
          onFocusedOptionChanged={this.onFocusedOptionChanged}
        />
      </div>
    );
  }
}

working demo: https://stackblitz.com/edit/react-z7izuy

EDIT: version with additional prop onOptionSelected which will be called when option is selected by user. https://stackblitz.com/edit/react-wpljbl

like image 106
Wilhelm Olejnik Avatar answered Oct 17 '22 12:10

Wilhelm Olejnik


I solved it by using onChange props.

  1. UI/Select component

      class CustomSelect extends React.PureComponent<IProps> {
        handleChange = (selectedOption: any) => {
        if (this.props.onSelect) {
            this.props.onSelect(selectedOption);
        }
      };
    
      render() {
        const { data } = this.props;
        return (
          <Select
            onChange={this.handleChange}
            options={data}
          />
        );
      }
    

    }

    1. Parent where I used CustomSelect with react-router 4 (I have access to withRouter).

      class SelectParent extends React.Component<IProps> {
        onSelect = (option: any) => {
        const id = option.value;
        const { history } = this.props;
        history.push(`/category/${id}`);
      };
      
      render() {
        const { data } = this.props;
        return (
          <Select
          data={data}
          onSelect={this.onSelect}
        />);
        }
      }
      
      export default withRouter<any>(SelectParent);
      
like image 2
Елена Семенова Avatar answered Oct 17 '22 12:10

Елена Семенова