Today I have this inline if which works fine for me
<View style={{justifyContent: 'center'}}>
{returnDayPercentageChange() > 0 ? (
<Icon
style={{color: '#1CDC93', marginTop: 3}}
name="caretup"
size={10}
/>
) : (
<Icon
style={{color: '#FF6767', marginTop: 3}}
name="caretdown"
size={10}
/>
)}
</View>
It works well but I want besides that to have no Icon when the returnDayPercentage === 0, how can I do that?
CodePudding user response:
You can nest ternary operators.
{returnDayPercentageChange() > 0 ? (
<Icon
style={{color: '#1CDC93', marginTop: 3}}
name="caretup"
size={10}
/>) : (
returnDayPercentageChange() < 0 ?
<Icon
style={{color: '#FF6767', marginTop: 3}}
name="caretdown"
size={10}
/> : null)}
CodePudding user response:
There are several options. Here are three.
- You can add an abstraction layer by putting the Icons in a component.
const PercentageIcon = ({ returnDayPercentageChange }) => {
if (returnDayPercentageChange === 0) return null;
if (returnDayPercentageChange > 0) return (
// etc
If you want to show the component inline, you can nest ternary operators as @DavidScholz suggests. However some lint rules and configurations disallow this.
You can also use an IIFE (immediately invoked function expression) in the component body.
{(() => {
if (returnDayPercentageChange === 0) return null;
if (returnDayPercentageChange > 0) return <Icon1 /> // removed props for brevity
if (returnDayPercentageChange < 0) return <Icon2 />
})()}