After experimenting with react-jss for a few weeks, I am faced with the challenge of styling components efficiently. With numerous conditionals in these components, I am striving to avoid creating an excess of new components that essentially share the same code. The flexibility of incorporating logic in styles through JS is a major advantage compared to the traditional method of conditional class name application.
Here is an example of a complex style that I have been working on:
color:
props.inactive && (props.buttonType === 'outline' || props.buttonColor === 'red')
? colors.greyscaleReg
: props.buttonColor === 'red'
? colors.primaryRed
: props.buttonType === 'outline'
? colors.primaryBlue
: props.buttonType === 'lightFill'
? colors.primaryBlue
: colors.white,
Personally, I am comfortable with ternaries and can easily navigate through this code. However, some of my colleagues are not fond of nested/chained ternaries like this.
Would it be recommended to extract this logic from the styles?
One suggestion was to create a function to house this code and then call that function within the styles (although an external function cannot be used for hover and may not calculate correctly).
I am not particularly fond of the following approach:
backgroundColor: () => {
if (props.inactive) {
return colors.greyscaleLight;
}
if (!props.loading && !props.inactive) {
if (props.buttonType === 'outline') {
return colors.secondaryPaleBlue;
}
if (props.buttonType === 'lightFill') {
return colors.secondarySoftBlue;
}
} else if (props.buttonColor === 'red') {
return colors.secondaryDarkRed;
}
return colors.darkPrimaryBlue;
},