VirtualList Demo

by Jason Miller

HTML

<script src="https://npmcdn.com/preact"></script>
<script src="https://npmcdn.com/preact-virtual-list"></script>
VirtualList renders only the visible items in a list. It updates on resize/scroll.

CSS

body { font:16px/1.21 'Helvetica Neue',arial,sans-serif; font-weight:300; }

.list {
	position: absolute;
	top: 20%;
	left: 20%;
	height: 60%;
	width: 60%;
	border: 1px solid #CCC;
	background: #FFF;
	overflow: auto;
	-webkit-overflow-scrolling: touch;
}

.row {
	position: relative;
	display: block;
	height: 30px;
	line-height: 30px;
	padding: 0 20px;
	box-shadow: inset 0 -1px 0 #DDD;
	overflow: hidden;
}

.row:focus {
  border: 1px solid gold;
}

Babel + JSX

const { h, Component, render } = preact;
/** @jsx h */

// static data
const DATA = [];
for (let x=1e5; x--; ) DATA[x] = { id:x, value: `Item #${x+1}` };

class Demo extends Component {
	rowHeight = 30;
	
	renderRow = row => (
		<Row
			row={row}
			focussed={this.state.focussed===row.id}
			onFocus={this.linkState('focussed', 'id')}
		/>
	);
	
	componentDidUpdate() {
		let focussed = this.base.querySelector(':focus');
		if (focussed) focussed.scrollIntoViewIfNeeded();
	}
	
	render() {
		return (
			<VirtualList
				sync
				class="list"
				data={DATA}
				rowHeight={this.rowHeight}
				renderRow={this.renderRow}
			/>
		);
	}
}

class Row extends Component {
	focus = () => {
		let { row, onFocus } = this.props;
		onFocus(row);
	};
	
	componentDidUpdate() {
		if (this.props.focussed) {
			this.base.focus();
		}
	}

	render({ row, focussed, onFocus, ...props }) {
		return (
			<a href='#' class="row" onFocus={this.focus} {...props}>
				{row.value}
			</a>
		);
	}
}

render(<Demo />, document.body);