Rule proposal: No return ternary
MikaelSiidorow opened this issue · 1 comments
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.
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.