Skip to content

Instantly share code, notes, and snippets.

@jquense
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jquense/c252e7abbcec036bf930 to your computer and use it in GitHub Desktop.
Save jquense/c252e7abbcec036bf930 to your computer and use it in GitHub Desktop.
DropdownList multiple disabled items
var DisabledList = React.createClass({
// proptypes tell the parent widget what to pass into it
// the DropdownList will inspect propTypes and _.pick() those keys to pass in
propTypes: {
disabledItems: React.PropTypes.array,
...List.type.propTypes,
},
componentWillMount(){
var parent = this
// we need to use a closure to allow the list item to know whether its disabled or not.
// do this infrequently though b/c it is costly, hence we cache it in state
this.setState({
listItem: React.createClass({
render() {
// add css rules to make it look "disabled"
var classes = parent.isDisabled(this.props.item) ? 'rw-state-disabled' : ''
return <div className={classes}>{this.props.item.name}</div>
}
})
})
},
render() {
return (
<List {...this.props}
ref='list'
itemComponent={this.state.listItem}
onSelect={ item => {
if (!this.isDisabled(item))
this.props.onSelect(item) // only allow selection of non-disabled items
}}
/>
)
},
isDisabled(item){
return this.props.disabledItems
&& this.props.disabledItems.some( id => id === item.id )
},
// Get the next item in the sequence, but keep going if the next one is disabled
move(dir, item){
var stop = dir === 'next' ? this.refs.list.last() : this.refs.list.first()
, next = this.refs.list[dir](item);
while( next !== stop && this.isDisabled(next))
next = this.refs.list[dir](next)
return this.isDisabled(next) ? item : next
},
// -- These are the basic List methods that must be implemented
first() {
this.move('next', null)
},
last() {
this.move('prev', null)
},
next(...args){
var item = this.refs.list.next(...args)
return this.move('next', item)
},
prev(...args){
var item = this.refs.list.prev(...args)
return this.move('prev', item)
}
})
var MyDropdownList = React.createClass({
render(){
var disabled = this.props.disabled && !Array.isArray(this.props.disabled)
, items = Array.isArray(this.props.disabled) ? this.props.disabled : [];
return (
<DropdownList {...this.props}
disabled={disabled}
listComponent={DisabledList}
disabledItems={items}
/>
)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment