Why can't I use the ternary operator and arrow function in this way in JSX?

With babel-preset-react (EDIT: babel version: v6.26.0 ), the following expression fails with the error " Invalid left-hand side in arrow function parameters " ( try babel REPL ):

 true ? ("test") : x => 42 //FAILS, but only with `babel-preset-react` 

However, it works with a slight modification:

 true ? "test" : x => 42 //works fine 

Both of these scenarios work as expected in any other configuration.

This is mistake? Or is there something in the JSX parsing that causes this?

+5
source share
3 answers

Arrow functions are analyzed differently than normal functions. See Sort order .

Although an arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator priority over regular functions.

 let callback; callback = callback || function() {}; // ok callback = callback || () => {}; // SyntaxError: invalid arrow-function arguments callback = callback || (() => {}); // ok 

It should have something to do with the associativity of the triple operator (from right to left), see link

+2
source

The simple reason for this is that everything inside () is treated as a condition for evaluation and, therefore, tries to find matching expressions after it that you do not provide, and therefore it fails. Actually

 true ? ("test")? 1: 2 : x => 42 

just compiles to

 "use strict"; true ? "test" ? 1 : 2 : function (x) { return 42; }; 

Check out this demo.

+1
source

This is mistake. I created a problem on the babel github page: babel / babel # 7234 . This is recorded in Babylon 7.

+1
source

Source: https://habr.com/ru/post/1274777/


All Articles