ternary operator inside a component tag

Viewed 1854

Is it possible to use ternary operator within a built-in component tag? For instance, I am using Touchable Opacity from React Native (Native Base):

type ItemProps = {
  title: string;
  face: string;
};

export const Item: React.FunctionComponent<ItemProps> = ({
  title,
  face,
}) => {

  const [showAddFriendPage, setShowAddFriendPage] = useState(false);

  const toggleAddFriendPage = () => {
    setShowAddFriendPage(showAddFriendPage ? false : true);
  };

  return (
    <TouchableOpacity activeOpacity={0.8}
    onPress={() =>
      setShowAddFriendPage(true)
    }   >
      <View>
        <Thumbnail small source={{ uri: face }} style={styles.thumbnail} />
        <Text numberOfLines={1} style={styles.title}>
          {title}
        </Text>
        <AddFriendPage
          showAddFriendPage={showAddFriendPage}
          toggleShowPage={toggleAddFriendPage}
        />
      </View>
    </TouchableOpacity>
  );
};

Currently the onPress navigation is applied to all Items regardless of what title or face was used. I want to introduce a conditional navigation. For instance, if the

title == 'news'

then onPress.... Since we can't use if else statements within jsx, I was trying ternary operators:

 <TouchableOpacity activeOpacity={0.8}
 {title == 'news'? {
      onPress={() =>
      setShowAddFriendPage(true)
    }   
    } }
/>

But this clearly doesn't work. I get '...' expected.on title.

No value exists in scope for the shorthand property 'onPress'. Either declare one or provide an initializer.ts(18004)on onPressand

Cannot find name 'setShowAddFriendPage'.
3 Answers

you can do like this

         <TouchableOpacity activeOpacity={0.8}
              onPress={() =>{
               if(title == 'news'){
                setShowAddFriendPage(true)
                }
          }}   
          />

You can use spread operator (...) to conditionally add props to components.

<TouchableOpacity
    activeOpacity={0.8}
    {...(title == 'news' && { onPress: () => setShowAddFriendPage(true) })}
/>

This way component will have onPress prop whenever title equals to 'news'

Use useCallback to create an onPress function that has different behavior based on your condition.

const onPress = useCallback(() => {
  if (title === 'news') {
    setShowAddFriendPage(true)
  }
}, [title])

It has a dependency on title, so it will be re-created, and the component re-rendered only if title changes.

Then use it as such:

<TouchableOpacity activeOpacity={0.8} onPress={onPress}>
  {/* … */}
</TouchableOpacity>
Related