最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to toggle 'className' dynamically in react.js? - Stack Overflow

programmeradmin0浏览0评论

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>

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>
Share Improve this question edited Mar 26, 2019 at 8:21 Hamed Rahmani asked Mar 26, 2019 at 7:59 Hamed RahmaniHamed Rahmani 411 gold badge4 silver badges10 bronze badges 5
  • Hi, I want to help but I didn't really understand the problem. Please try to be clear about what you EXPECT to happen and what IS happening. – Sagi Rika Commented Mar 26, 2019 at 8:03
  • please put here relevant code frok and show us link(it will be easier to help you):stackblitz./edit/react-pzyyha – לבני מלכה Commented Mar 26, 2019 at 8:06
  • 1 Why did you use "className" twice ? – Ibra Commented Mar 26, 2019 at 8:07
  • Can you share the whole ponent? – 0DDC0 Commented Mar 26, 2019 at 8:31
  • I Really didn't thinks that made the problem! thanks – Hamed Rahmani Commented Mar 26, 2019 at 9:10
Add a ment  | 

4 Answers 4

Reset to default 2

If setState() works well, try this :

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

One of the most mon 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>;
  }
}

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>
)

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

发布评论

评论列表(0)

  1. 暂无评论