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!

asked Feb 22, 2021 at 0:28
\$\endgroup\$

1 Answer 1

2
\$\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 {
 //
 }
}
answered Mar 5, 2021 at 23:29
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.