0
\$\begingroup\$

I am styling my react native component according to some conditions, here the code, The question is how do I make this cleaner? functional style?

const configColors = (isSingle, isDarkMode) => {
  let colors = {};

  if (isDarkMode){
    colors = {
      ...colors,
      configAxisLabelColor : Colors.white,
      configAxisGridColor : Colors.gridLineGray
    }
  }else{
    colors = {
      ...colors,
      configAxisLabelColor : Colors.lineGray,
      configAxisGridColor : Colors.transparent
    }
  }

  if (isSingle && !isDarkMode) {
    return colors = { 
      ...colors, 
      configAxisColor: Colors.transparent,
      configLineColor: Colors.lineGreen,
      configTooltipBackground: Colors.lineGreen,
    }
  }
  if (isSingle && isDarkMode) {
    return colors = { 
      ...colors, 
      configAxisColor: Colors.white,
      configLineColor: Colors.lineBlue,
      configTooltipBackground: Colors.lineBlue,
    }
  }
  if (!isSingle && !isDarkMode) {
    return colors = { 
      ...colors, 
      configAxisColor: Colors.lightBarGray,
      configLineColor: Colors.lineGray,
      configTooltipBackground: Colors.lineBlue,
    }
  }

}

Thanks in advance!

\$\endgroup\$
1
\$\begingroup\$

I think what you are looking for is a ternary operator.

const configColors = (isSingle, isDarkMode) => {
  return {
      configAxisLabelColor : isDarkMode ? Colors.white : Colors.lineGray,
      configAxisGridColor : isDarkMode ? Colors.gridLineGray : Colors.transparent
      configAxisColor: isSingle ? (isDarkMode ? Colors.white: Colors.transparent) : Colors.lightBarGray
      // so on
  }

Another option that reads better could be to create a separate config for each possible combination you want to return.

const configColors = (isSingle, isDarkMode) => {

  const configSingleDark = {
    configAxisLabelColor : Colors.white,
    configAxisGridColor : Colors.gridLineGray
  }

  if (isSingle && isDarkMode) {
    return configSingleDark
  } else if (isSingle && !isDarkMode) {
    return configSingleLight
  } else {
    //
  }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.