handleChange(value) {
let difference = this.state.selected.filter(x => !value.includes(x));
console.log("Removed: ", difference);
this.setState({
selected: value
});
}
To get notified about addition
of values in react-select, i used onKeyDown
prop. This method( handleKeyDown
) will be called when user enters any manual value and hits enter
or tab
to add values like below:
<Select
inputValue={inputValue}
isClearable={false}
isMulti
onChange={this.handleChange}
onInputChange={this.handleInputChange}
onKeyDown={this.handleKeyDown}
placeholder="Type something and press enter..."
value={value}
/>
handleKeyDown = event => {
const { inputValue, value } = this.state;
if (!inputValue) return;
console.log("event.key:", event.key);
switch (event.key) {
case "Enter":
const newValues = inputValue.split(",").map(x => createOption(x));
this.setState({
inputValue: "",
value: [...value, ...newValues]
});
event.preventDefault();
break;
case "Tab":
this.setState({
inputValue: "",
value: [...value, createOption(inputValue)]
});
event.preventDefault();
break;
default:
console.log("Other events caught");
}
};
You can capture remove
event using onChange
prop. Below code shows that:
handleChange = (value, actionMeta) => {
console.group("Inside handleChange");
console.log(value);
console.log(`action: ${actionMeta.action}`); // will capture remove event
this.setState({ value });
};
You can experiment in below sandbox. Above mentioned example is present in Sandbox: https://codesandbox.io/s/react-codesandboxer-example-7r2y6
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.