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:
- check for each case
{authModal.mode === 'login' && <Login />}
{authModal.mode === 'register' && <SignUp />}
{authModal.mode === 'forgotPassword' && <ForgotPassword />}
- if/else inside function
{(() => {
if (authModal.mode === 'login') {
return <Login />;
}
if (authModal.mode === 'register') {
return <SignUp />;
}
return <ForgotPassword />;
})()}
- 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
I like to use objects for this spot.
I would use a
useMemo
with an object lookup: