Search code examples
react-nativeconditional-operator

How to have two separate styles for each condition of a ternary operator?


My app has a light mode and dark mode. I want to change the color of the text based on whether the user has the app in light or dark mode. Light mode has two separate styles written like this:

            <Text style={[styles.chromatic, styles.noteTxt]}>{f + ''}</Text>

When applying the dark mode to my code I am writing it like this:

            <Text style={theme === true ? [styles.chromatic, styles.darkNoteTxt] : [styles.chromatic, styles.noteTxt]}>{f + ''}</Text>

There are no errors but the color is not changing when switching back and forth between light and dark. Can anyone tell me why this doesn't work with two styles for each condition? I'm guessing it is a problem with the syntax. Any help would be appreciated.


Solution

  • Your conditions is not wrong, can you check theme value, is it const or state value (which can change to true or false)?

    However, I believe changing the theme as your code may not be the best practice, Otherwise you have to write conditions to every tag that you want to change theme. Instead, I would suggest

    const lightColors = {
      primary: 'white',
    };
    const DarkColors = {
      primary: 'black',
    };
    
    const mockMode = 'light';
    
    export const colors = mockMode === 'light' ? lightColors : DarkColors;

    replace mockMode with stage value instead