Home > other >  Is there a way to use 3 arguments on a inline if statement?
Is there a way to use 3 arguments on a inline if statement?

Time:08-18

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.

  1. 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
  1. If you want to show the component inline, you can nest ternary operators as @DavidScholz suggests. However some lint rules and configurations disallow this.

  2. 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 />
  })()}
  • Related