2

I have to do something like:

email ? do_this : icon ? do_that : do_something_else

This can be done very simple using nested ternary but this ESLint rule doesn't make this possible.

On their documentation they recommend to use if-else but I don't know how to implement this in my case

The code works fine with one ternary.

return (
  <td>
    {email ? (
       <span>...</span>
     ) : (
       <span>...</span>
     )}
  </td>

adding nested ternary would return that ESLint error and using if-else says that if is an unexpected token:

return (
  <td>
    {if(email) return ( <span>...</span>);
     else if(icon) return ( <span>...</span>);
     else return ( <span>...</span>);
     }
  </td>

Is it possible to solve this problem?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Leo Messi
  • 5,157
  • 14
  • 63
  • 125
  • 1
    I used to create a function that return a boolean in those cases – Jon Jul 02 '20 at 12:13
  • @FelixKling, it's the project's rule. I don't want to disable the rule but to find a workaround – Leo Messi Jul 02 '20 at 12:14
  • 1
    you can do : `{!!email && ..}`, `{!email && !!icon && ..}`, `{<!email && !icon && ..}` – samb102 Jul 02 '20 at 12:23
  • Does this answer your question? [How can I avoid nested ternary expressions in my code?](https://stackoverflow.com/questions/46272156/how-can-i-avoid-nested-ternary-expressions-in-my-code) – Heretic Monkey May 14 '21 at 20:35

3 Answers3

1

You can store the cell content in a variable:

let content;
if(email) {
  content = <span>...</span>;
} else if(icon) {
  content = <span>...</span>;
} else {
  content = <span>...</span>;
}

return <td>{content}</td>;
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

I find it useful to extract a complex functionality for readability:

import React from 'react';

// extracted functionality
const emailAction = (email, icon) => {
  if (email) {
    return <span>Do This</span>;
  } else {
    if (icon) {
      return <span>Do That</span>;
    } else {
      return <span>Do Something Else</span>;
    }
  }
};

// your Component
export const TableData = (props) => {
  return <td>{emailAction(props.email, props.icon)}</td>;
};

foxxycodes
  • 233
  • 2
  • 6
1

Another option is to use something like an enum to render:

if (email) {
 content = 'email';
else if (icon) {
 content = 'icon';
} else {
 content = 'other';
}

return (
 <td>
   {{
   email: <span>...</span>,
   icon:  <span>...</span>,
   other: <span>...</span>,
   }[content]}
 </td>);

This is explained in more detail here: https://reactpatterns.js.org/docs/conditional-rendering-with-enum/

Code-Conjurer
  • 154
  • 1
  • 5