VirtualList Demo

by tnhu

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;
}

header {
	padding: 10px;
	text-align: center;
}
header input {
	border-radius: 3px;
	border: 1px solid #abc;
	padding: 5px;
	margin-right: 5px;
	font-size: 100%;
}

Babel + JSX

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

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

class Demo extends Component {
	rowHeight = 30;

	state = {
		search: ''
	};

	setSearch = e => {
		this.setState({ search: e.target.value });
	};
	
	// filter for results based on current search
	filter = result => (
		result.toLowerCase().indexOf(this.state.search.toLowerCase())!==-1
	);

	// handles rendering a single row of data
	renderRow(row) {
		return <div class="row">{row}</div>;
	}
	
	render(props, state) {
		let data = state.search ? DATA.filter(this.filter) : DATA;
		return (
			<div>
				<header>
					<input type="text" placeholder="Search..." onInput={this.setSearch} />
					<em>(hint: try typing numbers)</em>
				</header>
				<VirtualList
					sync
					class="list"
					data={data}
					rowHeight={this.rowHeight}
					renderRow={this.renderRow}
				/>
			</div>
		);
	}
}

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