\$\begingroup\$
\$\endgroup\$
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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
default