Junior
Junior

Reputation: 31

react-select prevent menu to open onInputChange

I'm trying to use the react-select component as an input and a select component.

Doing so I would like to prevent the menu to open while the user is typing the input.

I just can't find a way to update this behavior by either a prop or updating the onInputChange method.

My problem if I decide to use a controlled state with the menuIsOpen prop is that I can't manage to reopen the Menu control is clicked.

Here is what I have so far, do you guys any idea of how this could be achieved ?

<StyledSelect
  components={{ IndicatorSeparator }}
  {..._.omit(this.props, [])}
  filterOption={() => true}
  inputValue={inputValue}
  onChange={value => {
    this.select.setState({ menuIsOpen: false });
    this.setState({ selectValue: value });
  }}
  onInputChange={(value, event) => {
    if (event && event.action === 'input-change') {
      this.setState({ inputValue: value });
    }
  }}
  openMenuOnClick={false}
/>

Example

Upvotes: 3

Views: 3436

Answers (1)

Laura
Laura

Reputation: 8630

I think you are in the right direction using onInputChange and I would add a controlled menuIsOpen props like the following code:

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      menuIsOpen: false
    };
  }

  openMenu = () => {
    this.setState({ menuIsOpen: !this.state.menuIsOpen });
  };

  onInputChange = (props, { action }) => {
    if (action === "menu-close") this.setState({ menuIsOpen: false });
  };

  render() {

    const DropdownIndicator = props => {
      return (
        components.DropdownIndicator && (
          <div
            onClick={this.openMenu}
            style={{ display: "flex", alignItems: "center" }}
          >
            <span style={{ marginLeft: 12 }}>kg</span>
            <components.DropdownIndicator
              {...props}
              onClick={() => {
                console.log("ici");
              }}
            />
          </div>
        )
      );
    };

    return (
      <Select
        components={{ DropdownIndicator }}
        options={options}
        onChange={this.onChange}
        onInputChange={this.onInputChange}
        menuIsOpen={this.state.menuIsOpen}
      />
    );
  }
}

The idea with this code is to fire an onClick event on the DropdownIndicator custom component.

Here a live example.

Upvotes: 3

Related Questions