Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid nested ternary ESLint error in JSX

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?

like image 959
Leo Messi Avatar asked Oct 31 '25 11:10

Leo Messi


2 Answers

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>;
like image 132
Felix Kling Avatar answered Nov 02 '25 00:11

Felix Kling


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>;
};

like image 28
foxxycodes Avatar answered Nov 02 '25 02:11

foxxycodes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!