skip to Main Content

The code below, eslint raises some error

{authModal.mode === 'login' ? <Login /> : authModal.mode === 'register' ? <SignUp /> : <ForgotPassword />}

Error: Do not nest ternary expressions. eslint(no-nested-ternary)

I have come up with 3 ways not to get the error:

  1. check for each case
{authModal.mode === 'login' && <Login />}
{authModal.mode === 'register' && <SignUp />}
{authModal.mode === 'forgotPassword' && <ForgotPassword />}
  1. if/else inside function
{(() => {
  if (authModal.mode === 'login') {
    return <Login />;
  }
  if (authModal.mode === 'register') {
    return <SignUp />;
  }
  return <ForgotPassword />;
})()}
  1. switch case inside function
{(() => {
  switch (authModal.mode) {
    case 'login':
      return <Login />;
    case 'register':
      return <SignUp />;
    case 'forgotPassword':
      return <ForgotPassword />;
    default:
      throw new Error('Invalid auth mode');
  }
})()}

I’m new to JS and want to know how people would deal with this. If some of my solutions should be avoided please let me know. Other solutions are also appreciated!

2

Answers


  1. I like to use objects for this spot.

    const autModal = {
      mode: 'login'
    }
    
    const modes = {
      login: <Login />,
      register: <Singup />
      forgotPassword: <ForgotPassword />
    }
    
    () => modes['authModal.mode']
    
    Login or Signup to reply.
  2. I would use a useMemo with an object lookup:

    const authComponent = useMemo(() => ({
      'login': <Login />,
      'register': <SignUp />,
      'forgotPassword': <ForgotPassword />
    })[authModal.mode], [authModal.mode]);
    
    return (
      <>
        {authComponent}
      </>
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search