3

A situation I have not ran into before due to way roles/authentication work in a project I am working on. On login, the code returns whether the user is just a user or an admin and renders the appropriate components, BUT if the user is an admin, I then need to conditionally evaluate API call returns and the type of category when someone searches. The data return from the box will be rendered in a component. There are three data types: user, group, account and these category values are retrieved from state with each API call return type. (user, group, account) Have to render different layouts for each of the 3 return data payloads.

Also, conditional rendering in the JSX page might be not the appropriate way to approach this, and please feel free to suggest a completely (and hopefully more elegant) way of doing something like this?

{isAdmin &&
  {isCategory === 'user'
     <User />
  }
  {isCategory === 'group'
     <Group />
  }
  {isCategory === 'account'
      <Account />
  }
}
 
{isUser &&
  <User />
}
1
  • Not sure if I understand what You are asking, but You probably just need to replace nested {}. They are not needed and actually are a syntax error. Try something like { isAdmin && ( (isCategory === 'user' && <User />) || (isCategory === 'group' && <Group />) ) }. You should use {} only inside an xml-like structures to "switch" syntax back to JS. After You do so - as You write regular JS - there is no need to use {} for embedding, as there is no jsx into which You need to embed. Commented Apr 25, 2021 at 2:21

1 Answer 1

4

Maybe clearer way is to create render function

const renderAdmin = () => {
  switch(isCategory) {
    case 'user':
      return <User />
    case 'group':
      return <Group />
    case 'account':
      return <Account />
    default:
      return null;
  }
}

and then in render

  <>
    {isUser &&  <User />}
    {isAdmin && renderAdmin()}
  </>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.