Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule proposal: No return ternary #3791

Open
MikaelSiidorow opened this issue Jul 26, 2024 · 1 comment
Open

Rule proposal: No return ternary #3791

MikaelSiidorow opened this issue Jul 26, 2024 · 1 comment

Comments

@MikaelSiidorow
Copy link

You might sometimes write a ternary at the top-level when returning from a React component

// incorrect code
function Component({ isCondition }: { isCondition: true }) {
  return isCondition ? (
    <Some>
      <Conditional />
    </Some>
  ) : (
    <Other>
      <Happy>
        <Path>
          <With />
          <More />
          <Stuff />
        </Path>
      </Happy>
    </Other>
  );
}

But a clearer version would be to have an early return, when there is no shared parent component. This reduces unnecessary nesting, which often leads to large diffs. It also makes it easier easier to differentiate the conditional renders on the component level and the happy path.

// correct code
function Component({ isCondition }: { isCondition: true }) {
  if (isCondition)
    return (
      <Some>
        <Conditional />
      </Some>
    );

  return (
    <Other>
      <Happy>
        <Path>
          <With />
          <More />
          <Stuff />
        </Path>
      </Happy>
    </Other>
  );
}

And of course it would still be valid to have ternaries that are not at top-level in a return.

// correct code
function Component({ isCondition }: { isCondition: true }) {
  return (
    <Container>
      {isCondition ? <NestedComponent /> : <OtherComponent />}
    </Container>
  );
}

I searched for such a rule, but didn't find anything existing. Therefore, I propose a new stylistic rule react/no-return-ternary. This rule would also match the code examples and documentation for conditional rendering in the React docs.

@ljharb
Copy link
Member

ljharb commented Jul 26, 2024

Hmm… "cleaner" is pretty subjective there - i can see the ternary form being cleaner because the two blocks of jsx are aligned and the non-jsx boilerplate is minimal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants