Reputation: 89
I am new to reactjs - looking to add some conditional class that come into action on the 3rd and 4th item in a loop
<div className={'medium-20 large-12 columns' + (index === 3 ? 'medium-push-10' : null)}>
if index 3 -- medium-push-10
if index 4 -- medium-pull-10
Upvotes: 2
Views: 6808
Reputation: 302
You can use this npm package. It automatically handles everything (string,array,objects,functions,null,undefined) and has options for static and conditional classes based on a variables with a simple syntax. All in 1kb.
// Support for string arguments
getClassNames('class1', 'class2');
// support for Object
getClassNames({class1: true, class2 : false});
// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], {
class5 : function() { return false; },
class6 : function() { return true; }
});
// "class1 class2 class3 class4 class6"
<div className={getClassNames('show',{class1: true, class2 : false})} />
// "show class1"
Upvotes: 1
Reputation: 3586
For a quick solution you can add another Conditional Operator inside the second result of the first Conditional Operator.
<div className={'medium-20 large-12 columns' + (index === 3 ? ' medium-push-10' : index === 4 ? ' medium-pull-10' : '')}>
Don't go to far with this however, otherwise your code will soon be unreadable.
Upvotes: 3