Skip to content

Instantly share code, notes, and snippets.

@fernandocamargo
Last active March 7, 2018 22:15
Show Gist options
  • Select an option

  • Save fernandocamargo/1e09720d24816ae2d712737399bceffe to your computer and use it in GitHub Desktop.

Select an option

Save fernandocamargo/1e09720d24816ae2d712737399bceffe to your computer and use it in GitHub Desktop.
// https://jsfiddle.net/2we0rmox/
const clear = type => filter => filter.type !== type;
const add = filter => ({ filters }) => {
const current = filters.filter(clear(filter.type));
return {
filters: !filter.value ? current : current.concat(filter),
};
};
const check = item => (status, filter) =>
!status ? status : String(item[filter.type]) === String(filter.value);
const apply = filters => item => filters.reduce(check(item), true);
class Something extends React.Component {
state = {
filters: [],
items: [
{ year: 2018, type: 'A' },
{ year: 2017, type: 'A' },
{ year: 2016, type: 'A' },
{ year: 2018, type: 'B' },
{ year: 2017, type: 'B' },
{ year: 2016, type: 'B' },
{ year: 2018, type: 'C' },
{ year: 2017, type: 'C' },
{ year: 2016, type: 'C' },
],
};
filterBy = type => ({ target: { value } }) =>
this.setState(add({ type, value }));
getItems = () => {
const { state: { filters, items } } = this;
return items.filter(apply(filters));
};
renderItem = ({ year, type }, key) => (
<li key={key}>
Year: {year} | Type: {type}
</li>
);
render() {
const { state: { filters }, filterBy, getItems, renderItem } = this;
const items = getItems();
return (
<form>
<div>
<span>Filters:</span>
<pre>{JSON.stringify(filters, null, 2)}</pre>
</div>
<div>
<label htmlFor="filter-by-year">
<span>Year: </span>
<select id="filter-by-year" onChange={filterBy('year')}>
<option value="">Any year</option>
<option value="2018">2018</option>
<option value="2017">2017</option>
<option value="2016">2016</option>
</select>
</label>
</div>
<div>
<label htmlFor="filter-by-type">
<span>Type: </span>
<select id="filter-by-type" onChange={filterBy('type')}>
<option value="">Any type</option>
<option value="A">Type A</option>
<option value="B">Type B</option>
<option value="C">Type C</option>
</select>
</label>
</div>
<ul>{items.map(renderItem)}</ul>
</form>
);
}
}
ReactDOM.render(<Something />, document.getElementById('container'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment