Last active
October 21, 2015 10:01
-
-
Save flyingzl/cb1528bbfcd08b42c3e0 to your computer and use it in GitHub Desktop.
Think in React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var App = (props) =>{ | |
return <ProductFilterTable items={props.items} /> | |
} | |
var ProductFilterTable = React.createClass({ | |
getInitialState: function(){ | |
return { | |
text: "", | |
onlyStock:false | |
} | |
}, | |
handleFilter: function( filterText, onlyStock ){ | |
this.setState({ | |
text: filterText, | |
onlyStock: onlyStock | |
}); | |
}, | |
render: function(){ | |
return ( | |
<div> | |
<ProductSeachBar handleFilter={this.handleFilter} /> | |
<ProductTable | |
filterText= {this.state.text } | |
inStockOnly= {this.state.onlyStock} | |
items={this.props.items} /> | |
</div> | |
) | |
} | |
}) | |
var ProductSeachBar = React.createClass({ | |
doChange : function(){ | |
this.props.handleFilter(this.refs.text.value, this.refs.stock.checked); | |
}, | |
render: function(){ | |
return ( | |
<div> | |
<input onChange={this.doChange} ref="text" /> | |
{' '} Only show products in stock | |
<input type="checkbox" ref="stock" onChange={this.doChange} /> | |
</div> | |
) | |
} | |
}); | |
var ProductTable = (props) =>{ | |
var items = props.items, | |
rows = [], | |
lastCategory = ""; | |
items.forEach( (item, index) => { | |
if( item.name.indexOf(props.filterText) == -1 || !item.stocked && props.inStockOnly){ | |
return; | |
} | |
if(item.category != lastCategory ){ | |
lastCategory = item.category; | |
rows.push(<ProductRowCategory key={item.category} category={item.category} />) | |
} | |
rows.push(<ProductRow key={ item.category + index} item={item} />) | |
}) | |
return ( | |
<dl> | |
{rows} | |
</dl> | |
) | |
} | |
var ProductRowCategory = (props) =>{ | |
return ( | |
<dt style={{fontWeight:'bold'}}>{props.category}</dt> | |
) | |
} | |
var ProductRow = (props) => { | |
var item = props.item, | |
style = {}; | |
!item.stocked && ( style.color = 'red') | |
return ( | |
<dd style={style}>{item.name}{item.price} </dd> | |
) | |
} | |
var PRODUCTS = [ | |
{category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'}, | |
{category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'}, | |
{category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'}, | |
{category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'}, | |
{category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'}, | |
{category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'} | |
]; | |
ReactDOM.render(<App items={PRODUCTS} /> , document.getElementById("container") ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Snapshot as follow
