Skip to content Skip to sidebar Skip to footer

On/off Toggle For Filtering Content React

This React code is filtering variables according to the 'tag' which it contains (as seen in the list array). However, I cannot toggle the filter variables (tags) on/off. I want to

Solution 1:

In order to toggle the filters, you will need to check for the existence of the tag in the existing displayedCategories, look through the array for the tag, and then either remove it or add it in.

It is normally my preference to try to be functional so that assignment cannot cause confusion, so I will use a mostly functional style.


First to check for the presence of the tag we can use a filter operation.

var filteredCategories = this.state.displayedCategories
                             .filter(function (existingTag) {
    return existingTag.taglevel !== tag.taglevel ||
           existingTag.id !== tag.id;
});

So we now have a list of tags that are filtered to only include those that don't match the passed tag. We can check if the filtered list is the same size as the old list to see if we removed one. Alternatively, we could have filtered the other way around to see if we needed to remove one using some.

if (filteredCategories.length === this.state.displayedCategories.length){
    // tag wasn't present, add it
} else {
    // tag was present, use filtered list.
}

As I said above, I prefer functional, so we can do it slightly differently:

var newCategories = filteredCategories.length === this.state.displayedCategories.length ?
    filteredCategories.concat([tag]) :
    filteredCategories;

and then we need to set state:

this.setState({
    displayedCategories: newCategories,
});

To combine those together:

var filteredCategories = this.state.displayedCategories
                             .filter(function (existingTag) {
    return existingTag.taglevel !== tag.taglevel ||
           existingTag.id !== tag.id;
});

var newCategories = filteredCategories.length === this.state.displayedCategories.length ?
    filteredCategories.concat([tag]) :
    filteredCategories;

this.setState({
    displayedCategories: newCategories,
});

Post a Comment for "On/off Toggle For Filtering Content React"