Niranjan
Niranjan

Reputation: 2229

How to handle select event in select box?

Hi I am trying to implement select box in my react application. I am using npm from https://www.npmjs.com/package/react-select. Below is my code.

const options = [
  { value: 'Current', label: 'Current' },
  { value: 'Future', label: 'Future' },
  { value: 'Closed', label: 'Closed' },
];
export class EditParametersPanelComponent extends React.Component {
 this.state = {
 selectedOption: null,
 }
handleChange(selectedOption) {
    this.setState({ selectedOption });
    console.log('Option selected:', selectedOption);
  }

render() {
    const { selectedOption } = this.state;
       return (
       <Select
              instanceId="storeFilter"
              value={selectedOption}
              onChange={this.handleChange}
              options={options}
              placeholder="Store"
            />,
         );
  }
}

I am able to render select box in web page. Whenever I click on any one of the option I am getting below errors.

1. Uncaught TypeError: this.setState is not a function
2. Warning: Failed prop type: You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`. 

Can someone help me to identify and fix this error? Any help would be greatly appreciated. Thanks

Upvotes: 0

Views: 892

Answers (1)

kkangil
kkangil

Reputation: 1746

you have to use arrow function for binding

handleChange = selectedOption => {
    this.setState({ selectedOption });
    console.log('Option selected:', selectedOption);
  }

or you can use other way below

<Select
              instanceId="storeFilter"
              value={selectedOption}
              onChange={this.handleChange.bind(this)}
              options={options}
              placeholder="Store"
            />,

Upvotes: 0

Related Questions