I'd use an IIFE instead, so you can if/else.

{
  (() => {
    if (var1 && var2) return <Tag1 />;
    if (error) return <Tag2 />;
    return null;
  })()
}

For the MyApp component, this simplifies to:

const MyApp = () => {
    if (var1 && var2) return <Tag1 />;
    if (error) return <Tag2 />;
    return null;
};
Answer from CertainPerformance on Stack Overflow
Top answer
1 of 16
44

Your alternatives here are basically:

  1. That if/else you don't want to do
  2. A switch combined with if/else

I tried to come up with a reasonable lookup map option, but it got unreasonable fairly quickly.

I'd go for #1, it's not that big:

if (res.distance == 0) {
    word = 'a';
} else if (res.distance == 1 && res.difference > 3) {
    word = 'b';
} else if (res.distance == 2 && res.difference > 5 && String(res.key).length > 5) {
    word = 'c';
} else {
    word = 'd';
}

If all the braces and vertical size bother you, without them it's almost as concise as the conditional operator version:

if (res.distance == 0) word = 'a';
else if (res.distance == 1 && res.difference > 3) word = 'b';
else if (res.distance == 2 && res.difference > 5 && String(res.key).length > 5) word = 'c';
else word = 'd';

(I'm not advocating that, I never advocate leaving off braces or putting the statement following an if on the same line, but others have different style perspectives.)

#2 is, to my mind, more clunky but that's probably more a style comment than anything else:

word = 'd';
switch (res.distance) {
    case 0:
        word = 'a';
        break;
    case 1:
        if (res.difference > 3) {
            word = 'b';
        }
        break;
    case 2:
        if (res.difference > 5 && String(res.key).length > 5) {
            word = 'c';
        }
        break;
}

And finally, and I am not advocating this, you can take advantage of the fact that JavaScript's switch is unusual in the B-syntax language family: The case statements can be expressions, and are matched against the switch value in source code order:

switch (true) {
    case res.distance == 0:
        word = 'a';
        break;
    case res.distance == 1 && res.difference > 3:
        word = 'b';
        break;
    case res.distance == 2 && res.difference > 5 && String(res.key).length > 5:
        word = 'c';
        break;
    default:
        word = 'd';
        break;
}

How ugly is that? :-)

2 of 16
40

To my taste, a carefully structured nested ternary beats all those messy ifs and switches:

const isFoo = res.distance === 0;
const isBar = res.distance === 1 && res.difference > 3;
const isBaz = res.distance === 2 && res.difference > 5 && String(res.key).length > 5;

const word =
  isFoo ? 'a' :
  isBar ? 'b' :
  isBaz ? 'c' :
          'd' ;
🌐
GitHub
github.com › eslint › eslint › issues › 3480
Add option to the `no-nested-ternary` rule that allows parens wrapped nested ternaries · Issue #3480 · eslint/eslint
August 21, 2015 - It'd be nice if there was an option for allowing parenthesis wrapped nested ternary expressions, i.e. {'no-nested-ternary': [2, {allowParensWrapped: true}]
Published   Aug 21, 2015
🌐
W3cubDocs
docs.w3cub.com › eslint › rules › no-nested-ternary
No-nested-ternary - ESLint - W3cubDocs
Nesting ternary expressions can make code more difficult to understand. ... The no-nested-ternary rule disallows nested ternary expressions.
🌐
GitHub
github.com › eslint › eslint › issues › 10321
Option to ignore no-nested-ternary for daisy-chained ternaries only · Issue #10321 · eslint/eslint
January 24, 2018 - 5:2 - Do not nest ternary expressions. (no-nested-ternary) 10:2 - Do not nest ternary expressions.
Published   May 06, 2018
Find elsewhere
🌐
Reddit
reddit.com › r/reactjs › [deleted by user]
Eslint disable no nested ternary. What to do? : r/reactjs
October 1, 2021 - Finally, if you decide you want to write nested ternaries and override eslint's recommendation - remember these recommended rulesets are usually made by fairly senior engineers, so that choice shouldn't be made lightly - you can target the rule it's complaining about, https://eslint.org/docs/rules/no-nested-ternary, and shut it off by writing something like this in your eslintrc:
🌐
GitHub
github.com › eslint › archive-website › blob › master › docs › 2.0.0 › rules › no-nested-ternary.md
archive-website/docs/2.0.0/rules/no-nested-ternary.md at master · eslint/archive-website
The no-nested-ternary rule aims to increase the clarity and readability of code by disallowing the use of nested ternary expressions.
Author   eslint
🌐
Reddit
reddit.com › r/react › nested ternary operators. how bad are they?
r/react on Reddit: Nested ternary operators. How bad are they?
January 26, 2024 -

So I saw an article recently that was talking about minimizing the use of ternary operators where possible and reflecting on my own use of them especially in JSX, I have a few questions...

Before I get decided to post my questions, I checked React subs and most discussions on this are a couple years old at least and I thought perhaps views have changed.

Questions:

  1. Is the main issue with using nested ternary operators readability?

I have found myself using ternary operators more and more lately and I even have my own way of formatting them to make them more readable. For example,

            info.type === "playlist"
            ?   info.creationDate
                ?   <div className="lt-info-stats">
                        <span className="text pure">Created on {info.creationDate}</span>
                    </div>
                :   null
            :   info.type === "artist"
                ?   <div className="lt-info-stats">
                        <span className="text pure">{info.genre}</span>
                    </div>
                :   <div className="lt-info-stats">
                        <span className="text pure">{info.releaseDate}</span>
                        <span className="cdot" style={{ fontWeight: "bold", margin: "1px" }}>·</span>
                        <span className="text pure">{info.genre}</span>
                    </div>

When written like this, I can visually see the blocks and tell them apart and it looks a lot like how an if/else might look.

nested ternary operator formatting

2. What is the preferred formatting of ternary operators in general and what do you think should be done to make them more readable?

3. How do people feel about nested ternary operators today? How big of a nono is it to have them in code (if it is a nono)?

I would love you know peoples thoughts on ternary operators in React in general as well.

Thanks for your attention!

🌐
Sonar
sonarsource.com › blog › stop-nesting-ternaries-javascript
Stop nesting ternaries in JavaScript | Sonar
December 7, 2023 - When you are intentional with your code and choose to minimise nesting and use fewer ternary operators, you will find your code is clearer and easier to understand and change over time. If you'd like a tool in your IDE to remind you of this as you type, install SonarQube for IDE for free. And if you're not already formatting your code, add Prettier to your project, too.
🌐
ESLint
archive.eslint.org › docs › rules › no-nested-ternary
no-nested-ternary
Nesting ternary expressions can make code more difficult to understand. ... The no-nested-ternary rule disallows nested ternary expressions.
🌐
ESLint
archive.eslint.org › docs › 4.0.0 › rules › no-nested-ternary
no-nested-ternary - Rules
Nesting ternary expressions can make code more difficult to understand. ... The no-nested-ternary rule disallows nested ternary expressions.
🌐
GitHub
github.com › eslint › eslint › blob › main › lib › rules › no-nested-ternary.js
eslint/lib/rules/no-nested-ternary.js at main · eslint/eslint
description: "Disallow nested ternary expressions", recommended: false, url: "https://eslint.org/docs/latest/rules/no-nested-ternary" }, · schema: [], · messages: { noNestedTernary: "Do not nest ternary expressions."
Author   eslint
🌐
GitHub
github.com › typescript-eslint › typescript-eslint › issues › 1819
[no-nested-ternary] rule was not found · Issue #1819 · typescript-eslint/typescript-eslint
January 5, 2020 - ES Lint provides a "no-nested-ternary" rule: https://eslint.org/docs/rules/no-nested-ternary I tried implementing it into my config: { "rules": { "@typescript-eslint/no-nested-ternary": "error" } } I received the following error: error D...
Published   Mar 28, 2020
🌐
Medium
medium.com › @benlmsc › stop-using-nested-ternary-operators-heres-why-53e7e078e65a
Stop using nested ternary operators. Here’s why. | by Ben Lmsc | Medium
February 12, 2023 - I still regularly see more or less ... using nested ternary operators. This is in my opinion a very bad practice. Let’s see in details why. Let’s imagine the following functionality: a prompt asking us for our hierarchical position and a modal asking us for confirmation. For the purpose of the demonstration, I will not use a switch ...
🌐
Drupal
drupal.org › project › ui_suite_bootstrap › issues › 3351482
Don't nest or chain ternary operators [#3351482] | Drupal.org
April 14, 2023 - Problem/Motivation There is something wrong about nesting ternary operators in general: ESlint is warning about them: https://eslint.org/docs/latest/rules/no-nested-ternary Sonar has many rules against them. Example for JS: https://rules.sonarsource.com/javascript/RSPEC-3358 Example for PHP: https://rules.sonarsource.com/php/RSPEC-3358 And it seems even more complicated in PHP (Twig is compiled to PHP before being executed): Unlike most (all?) other languages, the ternary operator in PHP is left-associative rather than right-associative.