Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!