filterProduct

by Van Hai Le

HTML

<div id="app"></div>

CSS

body {
	padding: 16px;
}

React

class SearchBox extends React.Component {
	constructor(props) {
		super(props);
		this.state = {userInput: ''}
		this.onChange = this.onChange.bind(this);
		this.onCheckboxChange = this.onCheckboxChange.bind(this);
	}
	onChange(event) {
		this.props.onChange(event.target.value);
		this.setState({userInput: event.target.value});
	}
	onCheckboxChange(event) {
		this.props.onCheckbox(event.target.checked);
	}
	render() {
		const filterText = this.props.filterText;
    const inStockOnly = this.props.inStockOnly;
		return (
			<form>
				<input
				type="text"
				placeholder='Search...'
				onChange={this.onChange}
				value={filterText}
				/>
				<p>
					<input 
					type="checkbox"
					checked={inStockOnly}
					onChange={this.onCheckboxChange}
					/>
					{' '}
					Only show products in stock
				</p>
			</form>
		);
	}
}

class ProductCategoryRow extends React.Component {
	render() {
		const category = this.props.category;
		return (
			<tr>
				<th colSpan='2'>
					{category}
				</th>
			</tr>
		);
	}
}

class ProductRow extends React.Component {
	render() {
		let product = this.props.product;
		let name = product.stocked ?
			product.name :
			<span style={{color: 'red'}}>
				{product.name}
			</span>
		return (
			<tr>
				<td>{name}</td>
				<td>{product.price}</td>
			</tr>
		);
	}
}

class ProductTable extends React.Component {
	
	render() {
		const rows = [];
		let lastCategory = null;
		
		const filterText = this.props.filterText;
		const inStockOnly = this.props.inStockOnly;
		
		this.props.products.forEach((product) => {
				if (product.name.toLowerCase().indexOf(filterText) === -1) {
					return;
				}
				if (inStockOnly && !product.stocked) {
					return;
				}
				if (product.category !== lastCategory) {
					rows.push(
						<ProductCategoryRow...