standard icon indicating copy to clipboard operation
standard copied to clipboard

JSX multiline ternaries indentation/placement

Open apennell opened this issue 5 years ago • 2 comments

What version of this package are you using? 16.0.3

What operating system, Node.js, and npm version? MacOS Catalina, Node v14.15.0, npm 6.14.8

What happened? Given the following code (which is how I would normally format a multiline ternary in jsx):

{somethingTrueOrFalse ? (
  <div>
    A true thing
  </div>
) : (
  <div>
    A false thing
  </div>
)}

standard --fix doesn't change anything, but does have the following errors:

  36:8   error  Expected newline between test and consequent of ternary expression
  36:31  error  Expected newline between consequent and alternate of ternary expression

If I run manually move the ? and : so they're the first thing on their respective lines and then run --fix several more times, it eventually reaches:

{somethingTrueOrFalse
  ? (
    <div>
      A true thing
    </div>
    )
  : (
    <div>
      A false thing
    </div>
    )}

What did you expect to happen? Echoing something similar as comments in #1564 and #1382, I would expect it to accept that original formatting for jsx, as the alignment required to satisfy the rules here doesn't seem consistent, like the curly brace end and parens don't end at the same indentation level as they started.

Are you willing to submit a pull request to fix this bug? If there's some guidance on how to approach it, I could be.

apennell avatar Nov 25 '20 02:11 apennell

As I mentioned in https://github.com/standard/standard/issues/1564#issuecomment-724430949, I believe we need ESLint to add a new option for the indent rule in order to fix the issue with the closing paren not being lined up. It should be like this:

{somethingTrueOrFalse
  ? (
    <div>
      A true thing
    </div>
  )
  : (
    <div>
      A false thing
    </div>
  )}

Unfortunately, there's no eslint rule for this case. If you're keen on this, can you open an issue over at ESLint at explain the issue. If they add it, then I'm happy to fix up standard to format code as you've indicated.

feross avatar Nov 25 '20 20:11 feross

Possible workaround is to use to use standardx and disable "multiline-ternary":0 in .eslintrc "extends":