Reputation: 4349
I am trying to do something similar to if elseif else
statement in React.
Here is what I have currently, with just simple true
or false
conditional, and works fine
{isAdmin() ? (
<>
<a href="/profile">admin</a>
<div class='container'></div>
</>
) : (
<>
<a href="/profile">user</a>
<div class='container'></div>
</>
)}
but now I want to have multiple conditionals. Tried this below
isAdminTwo()
and isAdminThree()
are children of isAdmin()
, which means that they all must meet isAdmin()
condition first
{isAdmin() ? (
<>
<a href="/profile">admin</a>
<div class='container'></div>
</>
) : (
<>
{isAdminTwo() ? (
<>
<a href="/profile">admin2</a>
<div class='container'></div>
</>
) : (
<>
{isAdminThree() ? (
<>
<a href="/profile">admin3</a>
<div class='container'></div>
</>
) : (
<>
<a href="/profile">user</a>
<div class='container'></div>
</>
)}
but getting errors
TypeError: ge(...) is not a function
What is a proper way to do this?
Upvotes: 0
Views: 74
Reputation: 858
To start off, you should not be doing that. Rather go for a syntax like
if (isAdmin())
return (
<>
<a href="/profile">admin</a>
<div class="container"></div>
</>
);
if (isAdmin() && isAdminTwo())
return (
<>
<a href="/profile">admin2</a>
<div class="container"></div>
</>
);
if (isAdmin() && isAdminThree())
return (
<>
<a href="/profile">admin3</a>
<div class="container"></div>
</>
);
return (
<>
<a href="/profile">user</a>
<div class="container"></div>
</>
);
Or if you want to use it within other component that is always the same:
let contents = (
<>
<a href="/profile">user</a>
<div class="container"></div>
</>
);
if (isAdmin())
contents = (
<>
<a href="/profile">admin</a>
<div class="container"></div>
</>
);
if (isAdmin() && isAdminTwo())
contents = (
<>
<a href="/profile">admin2</a>
<div class="container"></div>
</>
);
if (isAdmin() && isAdminThree())
contents = (
<>
<a href="/profile">admin3</a>
<div class="container"></div>
</>
);
return <SameWrapper>{contents}</SameWrapper>;
But if you wanted to do it with ternary operators (which would be most probably not readable for other people and you in the future), kepp in mind correct syntax of ternary operator:
truthCheck ? ifTrue : ifFalse
So your example should go along the way
isAdmin() ? (
isAdminTwo() ? (
<>
<a href="/profile">admin2</a>
<div class="container"></div>
</>
) : isAdminThree() ? (
<>
<a href="/profile">admin3</a>
<div class="container"></div>
</>
) : (
<>
<a href="/profile">admin</a>
<div class="container"></div>
</>
)
) : (
<>
<a href="/profile">user</a>
<div class="container"></div>
</>
);
Where your truthCheck
is there, and if true
display a component, but if false
perform next check. In your code these fragments are causing bugs:
<> // <--- these are not needed
{isAdminTwo() ? (
<> // <--- these are not needed
// same for below
Upvotes: 3