Home > Blockchain >  react native: Ternary condition inside Text component
react native: Ternary condition inside Text component

Time:04-29

Is it possible to make ternary condition so that if {title} contains part of text such as "appl" then 'styles.label' will be change to 'styles.label_2' .

const Field = ({ title, info }: Props) => {
  return (
    <View style={styles.container}>
      <Text style={styles.label}> {title} </Text>
      <Text style={styles.info}>{info ? info : ''} </Text>
    </View>
  );
};

CodePudding user response:

You can do that for sure.

The following checks if the title string contains appl and if so, use styles.label2 otherwise, use styles.label

<Text style={title.includes('appl') ? styles.label2 : styles.label}> {title} </Text>

CodePudding user response:

If you apply a second style only to hide when it evaluates to false, I prefer evaluating before rendering the component -- therefore if it evaluates to false, no component is ever present, instead of a empty one:

const Field = ({ title, info }: Props) => {
  return (
    <View style={styles.container}>
      <Text style={styles.label}> {title} </Text>
      {info && info.contains("appl") && (<Text style={styles.info}>{info} </Text>)}
    </View>
  );
};
  • Related