I am a beginner in developing with React. I learned with the Facebook documentation. I practice with the "Thinking in React" example (go to it). But I tried to change the solution by using nothing but functions. Here is the result :
function ProductCategoryRow({category, key}) {
return <tr><th colSpan="2">{category}</th></tr> ;
}
function ProductRow({product, key}) {
var name = product.stocked ? product.name :
<span style={{color: 'red'}}>
{product.name}
</span>;
return (
<tr>
<td>{name}</td>
<td>{product.price}</td>
</tr>
);
}
function ProductTable({products, filterText, inStockOnly}) {
var rows = [];
var lastCategory = null;
products.forEach((product) => {
if (product.name.indexOf(filterText) === -1 || (!product.stocked && inStockOnly)) {
return;
}
if (product.category !== lastCategory) {
rows.push(<ProductCategoryRow category={product.category} key={product.category} />);
}
rows.push(<ProductRow product={product} key={product.name} />);
lastCategory = product.category;
});
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}
function handleFilterTextInput(event) { filterText = event.target.value; refresh() }
function handleInStockInput(e) { inStockOnly = e.target.checked; refresh()}
function SearchBar({filterText, inStockOnly, onFilterTextInput, onInStockInput}) {
return (
<form>
<input
type="text"
placeholder="Search..."
value={filterText}
onChange={onFilterTextInput}
/>
<p>
<input
type="checkbox"
checked={inStockOnly}
onChange={onInStockInput}
/>
{' '}
Only show products in stock
</p>
</form>
);
}
var filterText = "";
var inStockOnly = false;
function FilterableProductTable({products}) {
return (
<div>
<SearchBar
filterText={filterText}
inStockOnly={inStockOnly}
onFilterTextInput={handleFilterTextInput}
onInStockInput={handleInStockInput}
/>
<ProductTable
products={PRODUCTS}
filterText={filterText}
inStockOnly={inStockOnly}
/>
</div>
);
}
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'}
];
function refresh() {
ReactDOM.render(
<FilterableProductTable products={PRODUCTS} />,
document.getElementById('container')
);
}
refresh();
It works well but :
- could I go on this way ?
- is there any method to refresh de document in a better way that re-render from the root of the tree ?
Any other comment would be appreciated