calvert
calvert

Reputation: 721

React select is not selecting option

https://codesandbox.io/s/o7z5rxmq4z

I have the code sandbox attached and it is a simplified version of my actual app. I tried clicking on the options but none of them is being selected in the React Select v1 options.

This is my container file. If I remove the val in return( <div> <SelectComponent/> which is the value of the select component and it will show whatever I chose but I need the value props. I need the value props so that I can submit the value to my server.

Also if I replace await this.setState({ val: event.value }) with await this.setState({ val: event.val }), the component will show the chosen option but the val will be undefined.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      val: null
    };
  }

  handleChange = async event => {
    event !== null
      ? await this.setState({ val: event.value })
      : await this.setState({ val: null });
  };
  render() {
    let fruitArray = [
      { value: "apple", label: "Apple" },
      { value: "orange", label: "Orange" },
      { value: "watermelon", label: "Watermelon" }
    ];
    return (
      <div>
        <SelectComponent
          val={this.state.val}      
          select_id="fruit_select_id"
          select_options={fruitArray}
          select_placeholder="Choose a fruit"
          handle_change={this.handleChange}
        />
      </div>
    );
  }
}

This is my select component file. I tried this with a stateless version too but the outcome are the same, nothing is being selected.

class SelectComponent extends Component {
  render() {
    const {
      select_id,
      select_options,
      handle_change,
      select_placeholder,
      val
    } = this.props;
    return (
      <div>
        <Select
          value={val}
          id={select_id}
          name={select_id}
          options={select_options}
          onChange={handle_change}
          placeholder={select_placeholder}
          isClearable
        />
      </div>
    );
  }
}

Can anyone tell me what went wrong?

Upvotes: 2

Views: 2240

Answers (2)

larz
larz

Reputation: 5766

1 - no reason for any of the async/await stuff. That will just muck with React.

handleChange = event => this.setState({ val: event.value });

2 - You're passing val to your SelectComponent but you need to pass value;

<SelectComponent
      value={this.state.val}      
      select_id="fruit_select_id"
      select_options={fruitArray}
      select_placeholder="Choose a fruit"
      handle_change={this.handleChange}
/>

Upvotes: 0

Tholle
Tholle

Reputation: 112897

The Select component wants the entire selected option object as the value prop. If you put the entire object in state instead of just the value property, it will work.

handleChange = option => {
  this.setState({ val: option });
};

Upvotes: 3

Related Questions