Type Script - React Native : What is the best practice way to write ternary inside ternary?

Viewed 53

What is the best practice way to write ternary inside ternary like in my example code? I want to make the code more readable and correct and I want to know the correct way to write it.

         <TouchableOpacity
            style={
              darkMode
                ? filterState === 'A'
                  ? styles.activeButtonDark
                  : styles.buttonDark
                : filterState === 'A'
                ? styles.activeButton
                : styles.button
            }
           
          >
          </TouchableOpacity>

<TouchableOpacity
            style={
              darkMode
                ? filterState === 'B'
                  ? styles.activeButtonDark
                  : styles.buttonDark
                : filterState === 'B'
                ? styles.activeButton
                : styles.button
            }
            
          >
          </TouchableOpacity>
1 Answers

Nested Ternary inside ternary will never be a good approach, readability wise

rather than this you can try with :

const darkModeStyle = (filterState) => {
 return filterState === 'A' ? styles.activeButtonDark : styles.buttonDark 
} 

const lightModeStyle = (filterState) => {
return filterState === 'A' ? styles.activeButton : styles.button
}


style = {
  darkMode ? darkModeStyle(filterState) : lightModeStyle(filterState)
}

This is still a better approach, or you can use SwitchCase or if else in a separate func.

Hope it helps. feel free for doubts

EDIT:

If else to be like this

const styleGenerator = (darkMode = false, filterState = "A") => {
  if (darkMode) {
    if (filterState === 'A') {
      return styles.activeButtonDark
    }
     if (filterState === 'B') {
      return styles.stylesNew
    }
    return styles.buttonDark
  } else {
    if (filterState === 'A') {
      return styles.activeButton
    }
  if (filterState === 'B') {
      return styles.newStyle
    }
    return styles.button
  }
}




style = {
  styleGenerator(darkMode, filterState)
}
Related