Hamed Rahmani
Hamed Rahmani

Reputation: 41

How to toggle 'className' dynamically in react.js?

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>

Upvotes: 3

Views: 13358

Answers (4)

Sujith Sandeep
Sujith Sandeep

Reputation: 1247

We can toggle class name dynamically like below,

const [islight, setIslight] = useState(false)
const toggle = () => {
    setIslight(!islight)
}

return (
   <div className={`block ${islight ? "blocklight" : "blockdark"}`}>
      <h2>Hello World</h2>
   </div>
)

Upvotes: 1

Ibra
Ibra

Reputation: 1054

If setState() works well, try this :

<a onClick={this.handleRemoveFilter}
        className={ this.state.selectedCategoryId === 0 ? 'pointer active' : 'pointer'}
>All tags</a>

Upvotes: 2

Tony Yip
Tony Yip

Reputation: 750

One of the most common ways is to use classnames which you can conditionally joining classNames together

var classNames = require('classnames');

class Button extends React.Component {
  // ...
  render () {
    var btnClass = classNames({
      btn: true,
      'btn-pressed': this.state.isPressed,
      'btn-over': !this.state.isPressed && this.state.isHovered
    });
    return <button className={btnClass}>{this.props.label}</button>;
  }
}

Upvotes: 1

Gaurav Mithas
Gaurav Mithas

Reputation: 75

store classname in state along with selected item. You can just update the classname in state whenever required.

for eg,

  <a key={item.id}
            onClick={() => this.handleFilter(item.id)}
            className={this.state.activeClassName}

where active classname can be updated inside handlefilter

Upvotes: 0

Related Questions