Skip to content

Instantly share code, notes, and snippets.

@jamesjjk
Created September 1, 2015 16:01
Show Gist options
  • Save jamesjjk/79a7b76a877d77baaa46 to your computer and use it in GitHub Desktop.
Save jamesjjk/79a7b76a877d77baaa46 to your computer and use it in GitHub Desktop.
How to limit number of selection for the react widget multiselector.
class MultiSelector extends React.Component {
static propTypes = {
valueField: PropTypes.string.isRequired,
textField: PropTypes.string.isRequired,
limit: PropTypes.number,
placeholder: PropTypes.string,
label: PropTypes.string,
items: PropTypes.array.isRequired
}
static defaultProps = {
limit: 10,
valueField: 'id',
textField: 'name',
placeholder: 'Select or search...'
}
state = {
items: [],
value: [],
searchTerm: null,
open: false
}
constructor(props) {
super(props);
}
componentWillReceiveProps(nextProps) {
this.setState({
items: nextProps.items
})
}
_create(name){
let tag = { name: upperCaseWords(name), id: this.state.items.length + 1 } //delete ID when serialising
let value = this.state.value.concat(tag);
let items = this.state.items;
this.setState({ value: value, items: this.state.items.concat([tag]) })
}
_change(values){
if (values.length <= this.props.limit) {
this.setState({ value: values })
}
}
_search(searchTerm){
if (this.state.value.length < this.props.limit) {
this.setState({ searchTerm: searchTerm })
}
}
_toggle(isOpen){
if (isOpen === true && this.state.value.length < this.props.limit) {
this.setState({ open: true })
} else {
this.setState({ open: false })
}
}
render() {
console.log(this.props.limit)
return (
<div>
<h3>{this.props.label}</h3>
<Multiselect
valueField={this.props.valueField}
textField={this.props.textField}
searchTerm={this.state.searchTerm}
value={this.state.value}
open={this.state.open}
minLength={2}
filter='contains'
placeholder={this.props.placeholder}
onCreate={this._create.bind(this)}
onChange={this._change.bind(this)}
onSearch={this._search.bind(this)}
onToggle={this._toggle.bind(this)}
data={this.state.items}/>
</div>
);
}
}
export default MultiSelector;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment