javascript - Reactjs multiple conditional classes - Stack Overflow

I am new to reactjs - looking to add some conditional class that e into action on the 3rd and 4th item

I am new to reactjs - looking to add some conditional class that e 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

I am new to reactjs - looking to add some conditional class that e 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
Share Improve this question asked May 26, 2017 at 13:28 The Old CountyThe Old County 13914 gold badges67 silver badges142 bronze badges 3
  • You could add to the ternary as mentioned in the answer. Or, if you're testing several conditions, why not just add a new function that returns the desired class? <div className={ this.giveMeMyClass(index) } – Skäggiga Mannen Commented May 26, 2017 at 13:49
  • That's a good idea too - well - take a peak at the concept in the ment to that answer – The Old County Commented May 26, 2017 at 13:54
  • Does this answer your question? ReactJS conditional ponent display – Aliasghar Ahmadpour Commented Feb 18, 2022 at 14:55
Add a ment  | 

2 Answers 2

Reset to default 3

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.

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"

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745376403a4625020.html

相关推荐

  • javascript - Reactjs multiple conditional classes - Stack Overflow

    I am new to reactjs - looking to add some conditional class that e into action on the 3rd and 4th item

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信