Home > Software design >  How to add ternary operator to an on press event
How to add ternary operator to an on press event

Time:09-27

I have the following code in a react native component:

            renderItem={({item, index, section})=> {
               return (
                 <View style={{ backgroundColor: index % 2 == 1 ? "#F0FBFC" : "white" }}>
                   <TouchableOpacity style={styles.touchableRow} onPress={ () => navigateMember(absentData[item].uid, section.title) }>
                     <Text style={styles.columnRowTxt}>{item.first}</Text>
                     <Text style={styles.columnRowTxt}>{item.last}</Text>
                     <Text style={styles.columnRowTxt}>{item.phone}</Text>
                   </TouchableOpacity>
                 </View>
               )
             }}

If section.title == "Absent" I need to onPress to be as is:

onPress={ () => navigateMember(absentData[item].uid, section.title) } but if it's not I need it to be 
onPress={ () => navigateMember(visitData[item].uid, section.title) } can this be done in a ternary operator?  Currently it's not working for me.  I can do a method but I'm wondering if there is away to do it as a ternary.  I tried:

{sectionList.title == "Absent" ? (
onPress={ () => navigateMember(absentData[item].uid, section.title) }
) : (
onPress={ () => navigateMember(visit[item].uid, section.title) }
)}

The above errored. I feel like I'm just making up syntax there. Any idea if it can be done?

CodePudding user response:

The only thing that changes is the first argument, so the conditional operator only needs to replace the first argument.

onPress={ () => navigateMember((sectionList.title === "Absent" ? absentData : visitData)[item].uid, section.title) }

But it'd be more readable to create a block for the function so you can extract the uid in the first line.

onPress={ () => {
  const { uid } = (sectionList.title === "Absent" ? absentData : visitData)[item];
  return navigateMember(uid, section.title);
}}

CodePudding user response:

There are multiple ways to do this

  1. Condition for specific parameter
onPress={() => navigateMember(sectionList.title == "Absent" ? absentData[item].uid : visit[item].uid, section.title)}
  1. if else
onPress={ () => {
  if(sectionList.title == "Absent"){
    navigateMember(absentData[item].uid , section.title)}
  } else {
    navigateMember( visit[item].uid, section.title)}
  }
}
  • Related