Skip to content

Instantly share code, notes, and snippets.

@jquense
Created September 25, 2015 11:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jquense/3402adbda1f54a666cc9 to your computer and use it in GitHub Desktop.
Save jquense/3402adbda1f54a666cc9 to your computer and use it in GitHub Desktop.
Custom List Component
import React from 'react';
import ListMovementMixin from 'react-widgets/lib/mixins/ListMovementMixin';
import List from 'react-widgets/lib/List';
import ListOption from 'react-widgets/lib/ListOption';
import { dataText } from 'react-widgets/lib/util/dataHelpers';
import cn from 'classnames';
import BaseVirtualList from 'react-list';
let VirtualList = React.createClass({
propTypes: {
...List.propTypes,
data: React.PropTypes.array,
listType: React.PropTypes.string,
itemHeight: React.PropTypes.number
},
mixins: [ ListMovementMixin ],
_data(){
return this.props.data
},
componentDidMount(){
this.move()
},
componentDidUpdate(){
this.move()
},
render(){
var self = this
, {
className, data, onSelect, listType
, optionComponent: Option = ListOption
, ...props } = this.props
let ItemComponent = this.props.itemComponent;
listType = listType || 'uniform'
function renderItem(idx, key) {
var style
, item = data[idx]
, focused = item === props.focused
, selected = item === props.selected;
if (listType === 'uniform' && props.itemHeight)
style = { height: props.itemHeight }; //ensure a fixed height otherwise the list may blow the stack
return (
<Option
key={key}
style={style}
dataItem={item}
focused={focused}
selected={selected}
onClick={onSelect && onSelect.bind(null, item)}
>
{ ItemComponent
? <ItemComponent item={item}/>
: dataText(item, props.textField)
}
</Option>
)
}
function renderItems(items, ref){
return (
<ul
ref={ref}
className={cn(className, 'rw-list')}
style={{ overflow: 'visible', maxHeight: 'none' }}
role='listbox'
>
{items}
</ul>
)
}
return (
<div className='rw-virtual-list-wrapper'>
<BaseVirtualList
ref='scrollable'
length={data.length}
useTranslate3d={true}
type={listType}
itemRenderer={renderItem}
itemsRenderer={renderItems}
itemSizeGetter={props.itemHeight ? ()=> props.itemHeight : null }
/>
</div>)
},
move(){
var scrollable = this.refs.scrollable
, idx = this._data().indexOf(this.props.focused);
if ( idx === -1 )
return
scrollable.scrollAround(idx);
}
})
export default VirtualList;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment