I am trying to, disable select list after unchecking checkbox and resetting the select value to default..but I am seeing the one I selected. I am using React-select for the select and options in this.
APP.js
const adultOptions = [{ value: '1', label: '1' },{ value: '2', label: '2' }];
class App extends Component {
state = {
disableSelect2: true
}
selectDisableHandler2 = () => {
const showSelect = this.state.disableSelect2;
this.setState({ disableSelect2: !showSelect });
}
render() {
return (
<>
<div className="Container">
<div>
<table style={{ borderStyle: "solid" }}>
<caption style={{ borderStyle: "inherit" }}>
<input type="checkbox"
onClick={this.selectDisableHandler2} />Room 2</caption>
<tbody>
<tr>
<th>Adult (18+)</th>
<th>Children (0-17)</th>
</tr>
<tr>
<td>
<Select
options={adultOptions}
isDisabled={this.state.disableSelect2}
defaultValue={this.state.disableSelect2 ? adultOptions[0] : null}/>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</>
);
}
}
export default App;
```[In the image after unchecking checkbox, the options value is set to "2" which I selected, but I wanted it to be default value i.e. "1" ][1]
[1]: https://i.stack.imgur.com/S5gjP.png
You need to handle the value of your select in your components state:
<Select
value={this.state.selectedOption}
isDisabled={this.state.disableSelect2}
options={adultOptions}
onChange={this.handleChange}
/>
Have the checkbox handler update it accordingly:
selectDisableHandler2 = () => {
const showSelect = this.state.disableSelect2;
this.setState({
disableSelect2: !showSelect,
selectedOption:
showSelect === true ? this.state.selectedOption : adultOptions[0]
});
};
Codesandbox:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.