javascriptandroidiosreact-native

Conditional styling of Text component in React Native


Why does this conditional styling work for Presseble, but at the same time doesn't work for Text? How can I make it correct for the Text component too?

<Pressable style={ () => { return flagA == 0 ? styles.pressable_1 : styles.pressable_2 } } >
<Text style={ () => { return flagA == 0 ? styles.text_1 : styles.text_2 } }>{L5}</Text>

Solution

  • It's not working for , because the style prop for does not accept a function in the same way does. For , the style prop can be a function that receives the pressed state as a parameter. However, for , the style prop expects a direct style object or an array of styles.

    To fix this for text, you can use a conditional expression to decide which style to apply.

    Correct Code:

    <Pressable style={() => (flagA == 0 ? styles.pressable_1 : styles.pressable_2)}>
      <Text style={flagA == 0 ? styles.text_1 : styles.text_2}>{L5}</Text>
    </Pressable>