Search code examples
reactjsbootstrap-4primereact

React Dynamic class toggle multiple


Hello I basically want to toggle multiple div from active to inactive based on id or key.

Why cant i do something like this ?

<div className={  (activeId === 2? 'activecolumn' :   'inactivecolumn') && 'card middlecolumn mb-10 pt-2 pb-2 pl-2'  }   id="2" onClick={toggleMiddle.bind( 2)} >

I had to do this

<div className={  (activeId === 2? 'activecolumn card middlecolumn mb-10 pt-2 pb-2 pl-2' :   'inactivecolumn card middlecolumn mb-10 pt-2 pb-2 pl-2')   }   id="2" onClick={toggleMiddle.bind( 2)} >

I wish this was easy to do inline it's not jquery anymore.


Solution

  • You can simplify this by using template literals

    <div 
      className={`${activeId === 2 ? 'activecolumn' : 'inactivecolumn'} card middlecolumn mb-10 pt-2 pb-2 pl-2`} 
      id="2" 
      onClick={toggleMiddle.bind(2)}
    > 
      ... 
    </div>
    

    The 1st one is incorrect because if you notice you are doing something like 'myTruthyString' && 'another string'. Javascript will return the last truthy value when using && operator with strings, in this case it will only return the 'another string'.

    This question/answer might explain it a little better than I did.