Reputation: 183
I am working on a project using React.js and I have this error using the eslint:
Do not nest ternary expressions
Here is my code:
const MyApp = () => {
return (
<>
{(var1 && var2) ? (
<Tag1 />
) : error ? (
<Tag2 />
) : null}
</>);
}
Do you know how can I do to solve that? I thought to use if, but I think I cannot in my case.
Upvotes: 6
Views: 22128
Reputation: 28654
Well you can move that logic outside JSX, e.g.
function Component(){
..........
let content = null;
if (var1 && var2) content = < Tag1 / > ;
else if (error) content = < Tag2 / > ;
return <>{content}</>
}
Upvotes: 2
Reputation: 44086
This is caused by the no-nested-ternaries eslint rule.
Linter rules are suggestions on how you should write your code, they point out best practices but not necessarily real "errors".
If it shows an "error" here, that is because someone (or a preconfigured ruleset) decided to enable this rule as "error level" for your project. Generally, there is no need to change your code unless you (or someone on your team) wants to forbid this style of coding. Technically, it is perfectly valid code and will work.
If you are on a team, talk with your team about the sense of that rule. If you are alone on your project, think if you want this rule or not and disable it in your .eslintrc
file.
Personally I think that most suggestions on how to write this code instead given in other answers make it a lot less readable, so I'd keep it as this and disable the rule if I were you.
Upvotes: 6
Reputation: 2102
Deal with it before reaching your return statement:
const MyApp = () => {
let outTag = null;
if (var1 && var2) {
outTag = <tag1 />;
}
else if (error) {
outTag = <Tag2 />;
}
return (
<>
{outTag}
</>);
}
Upvotes: -1
Reputation: 370689
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;
};
Upvotes: 9