In my React app I am trying to catch some event when checkbox is clicked in order to proceed some state filtering, and show only items are needed.
event
is coming from child's checkbox with some name
. There is 3 checkboxes, so I need to know the name
which one is clicked.
some of them
<input
type=checkbox
name=name1
onClick={filterHandler}
/>Something</div>
state is something like
state = {
items = [
{
name: name1,
useful: true
},{
name: name2,
useful: false
}],
filteredItems: []
}
here is the handler
filterHandler = (evt) => {
let checked = evt.target.checked;
let name = evt.target.name;
let filteredItems = this.state.items.filter(item => {
return item[name] === checked; // filtered [{...},{...}...]
});
// when filtered - push to state and show all from here in <ItemsList />
this.setState({ filteredItems })
}
ItemsList component for showing is like so:
<ItemsList
items={this.state.filteredItems.length === 0 ? this.state.items : this.state.filteredItems}
/>
When checkbox is one and only - its working fine. But I have three of those boxes -- complications appears:
1) when checking next box I operate with original un-filtered items array - so for this purpose I need already filtered array.
2) I cant use my filteredItems
array reviously filtered, because when unchecking box that array gets empty.To have 3rd temporary array seems a little weird.
I tried this way, pretty similar also
this.setState({
filteredItems: this.state.items.filter(item => {
if (item[name] === checked) {
console.log('catch');
return Object.assign({}, item)
} else {
console.log('no hits')
}
})
and this is almost good, but when uncheck filteredItems
are filled with opposite values ((
I feel there is a better approach, please suggest.