I want to set the active class dynamically in react.js but it's not working!
I'm using the setState() method to change the selected item.
this line of code not work .
className={selectedCategoryId === item.id ? 'active' : ''}
I think the setState() function does not work correctly...
const {open, selectedProduct, productCategory, filteredProducts, selectedCategoryId} = this.state;
const categoryItems = productCategory.map((item) =>
<a key={item.id}
onClick={() => this.handleFilter(item.id)}
className={selectedCategoryId === item.id ? 'active' : ''}
// className={()=>this.isActive(item.id)}
className="pointer"
>{item.value}</a>
);
this does not change the class:
handleFilter = (id) => {
const filteredItem = this.state.productList.filter(x => x.categoryId == id);
this.setState({filteredProducts: filteredItem, selectedCategoryId: id});
}
but this change the className correctly when select I all tags:
handleRemoveFilter = () => {
this.setState({filteredProducts: this.state.productList, selectedCategoryId: 0});
}
//-------------------------------
<div className="tag-list">
<a onClick={this.handleRemoveFilter}
className="pointer"
className={ this.state.selectedCategoryId === 0 ? 'active' : ''}
>All tags</a>
{categoryItems}
</div>