Reputation: 6166
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?
Upvotes: 4
Views: 3125
Reputation: 304
Another option is to use something like an enum to render:
if (email) {
content = 'email';
else if (icon) {
content = 'icon';
} else {
content = 'other';
}
return (
<td>
{{
email: <span>...</span>,
icon: <span>...</span>,
other: <span>...</span>,
}[content]}
</td>);
This is explained in more detail here: https://reactpatterns.js.org/docs/conditional-rendering-with-enum/
Upvotes: 2
Reputation: 263
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>;
};
Upvotes: 2
Reputation: 816364
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>;
Upvotes: 2