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

javascript - Reactjs multiple conditional classes - Stack Overflow

programmeradmin1浏览0评论

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"
发布评论

评论列表(0)

  1. 暂无评论