14

I'd like to use mixed operators in JSX, for example:

{datas && datas.map(function(data,i){ return <MyComponent key={i} />}) || []}

While this technically works, ES lint warns of 'no-mixed-operators'. Is this a safe pattern to use in JSX?

huge-iguana
  • 195
  • 2
  • 2
  • 11
  • Just turn off the lint rule? --> http://eslint.org/docs/rules/no-mixed-operators#when-not-to-use-it – lux Jan 27 '17 at 17:26
  • I realize I could do that. But I would like to know if using mixed use operators in JSX is a bad pattern and should be avoided. – huge-iguana Jan 27 '17 at 17:29
  • 4
    Of course you can use mixed operators; it's valid JavaScript. The lint complaint just wants you to properly parenthesize them. – lux Jan 27 '17 at 17:30

2 Answers2

34

From the ESLint documentation:

Disallow mixes of different operators (no-mixed-operators)

Enclosing complex expressions by parentheses clarifies the developer’s intention, which makes the code more readable. This rule warns when different operators are used consecutively without parentheses in an expression.

var foo = a && b || c || d;    /*BAD: Unexpected mix of '&&' and '||'.*/
var foo = (a && b) || c || d;  /*GOOD*/
var foo = a && (b || c || d);  /*GOOD*/

If you don’t want to be notified about mixed operators, then it’s safe to disable this rule.

Hope this helps.

Michal Cumpl
  • 997
  • 7
  • 12
  • 1
    Right, I didn't think this would apply JSX but if I simply do: `{(datas && datas.map(function(data,i){ return })) || []}` it works. Thanks. – huge-iguana Jan 27 '17 at 17:37
0

You can just Wrap in the parenthesis like this. It not going to show that warning.

{datas && (datas.map(function(data,i){ return <MyComponent key={i} />}) || [])}

It worked for me.

cbisum
  • 126
  • 1
  • 11