Nested ternary statements are still being reported despite the exception to JSX expressions

According to the rule S3358 (for js and ts), it states that JSX expressions are exempt to this check because we need nested ternaries to for conditional rendering.
However, this rule is still being thrown for us.

We are using SonarQube 10.3, and I’m using SonarLint in VSC locally in connected mode.
Both SonarQube and Sonarlint are reporting this issue.

This issue is being thrown both in jsx and tsx files.

Example code:

export function test() {
    const value = 1;

    return (
        <div>{value < 0 ? <p>Value is below 0</p> : value > 0 ? <p>Value is above 0</p> : <p>Value is zero</p>}</div>
    );
}

Hello Thom,

Thank you for your feedback. The JSX exception does not avoid raising an issue when nested conditionals are in the same JSXExpressionContainer (the JS between curly brackets). We allow nesting in separate JSXExpressionContainers as is shown in the rule definition. But we do not when it is done in the same JSXExpressionContainer as in your example.

For your example, I would suggest to rewrite it like this:

export function test() {
    const value = 1;
    let text = '';
    if (value < 0) {
        text = 'Value is below 0';
    } else if (value > 0) {
        text = 'Value is above 0';
    } else {
        text = 'Value is zero';
    }

    return (
        <div><p>{text}</p></div>
    );
}

We will adapt the rule definition to make this clearer.

Does that answer your question?

Best,
Ilia

I opened a ticket to track the documentation improvement here: [JS-152] - Jira

2 Likes

Hello Ilia,

Thanks for the clarification, the example I showed was just a reproduction of the issue, we have many cases in our actual code of this occuring so we’ve got to go and think of alternatives to do it.

I reckon the easiest solution is to separate it into function calls for something like this:

 {activeSortValue === undefined ? (
    <ArrowDownUp className="text-grey" />
) : activeSortValue === SortDirection.ASC ? (
    <ArrowUp className="text-primary" />
) : activeSortValue === SortDirection.DESC ? (
    <ArrowDown className="text-primary" />
) : null}

into

function getArrowIcon(activeSortValue: SortDirection | undefined) {
    if (activeSortValue === undefined) { 
        return  <ArrowDownUp className="text-grey" />
    }
    // ...etc
}
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.