react-reduce
Sometimes there is a need in "react" to implement filters in our application. The most common task of a filter is to filter the received list. The react-reduce
module provides a convenient filter set-up, while providing a separation between the displayed list and the filtering mechanism.
example usage
1. Create transformer, define filters
;; ;; { const products = mode: 'virtual' price: 10 name: 'product 1' mode: 'virtual' price: 50 name: 'product 2' mode: 'virtual' price: 500 name: 'product 3' mode: 'virtual' price: 1000 name: 'product 4' mode: 'real' price: 20 name: 'product 5' mode: 'real' price: 80 name: 'product 6' mode: 'real' price: 200 name: 'product 7' mode: 'real' price: 400 name: 'product 8' ; return <Transform toTransform=products transformers='modeFilter' 'priceFilter' > <ReactFragment> <ModeFilter ref=refsmodeFilter onChange=onChange/> <PriceFilter ref=refspriceFilter onChange=onChange/> <pre>JSON</pre> </ReactFragment> </Transform> ;};
2. Define filters
Each filter should have a transform
method, which will be fired (under the hood) after each filter change. The purpose of this method is to prepare a list according to the state of the filter.
Due to the fact that each filter can have a different form - I keep implementing the onChange
function and preparing the state for self-implementation. It is important that the self-implemented onChange
function should run the `onChange function passed in the props.
2.1. Example implementation of mode filter mechanism
;; static propTypes = onChange: PropTypesfunc defaultValue: PropTypesstring ; static defaultProps = {} value: 'all' ; state = ModeFilterdefaultProps; { return <select value=thisstatevalue onChange= this > <option value="all">all</option> <option value="virtual">virtual</option> <option value="real">real</option> </select> ; } { return thisstatevalue === 'all' ? list : list ; } { const value = eventtarget; this; }
2.2. Example implementation of price filter mechanism
;; static propTypes = onChange: PropTypesfunc defaultValue: PropTypesstring ; static defaultProps = {} value: 'all' ; state = ModeFilterdefaultProps; { return <select value=thisstatevalue onChange= this > <option value="all">all</option> <option value="less">price less than 100</option> <option value="greater">price greater than 100</option> </select> ; } { if thisstatevalue === 'all' return list; if thisstatevalue === 'less' return list; else if thisstatevalue === 'greater' return list; } { const value = eventtarget; this; }