0
\$\begingroup\$

Recently, one of my colleague decided to destructure the React-Native styles object this way:

const { header, headerHint, bodyContainer, body, normalText, buttonWrapper, button, footer, footerLinks } = styles;

And then used the variables in the React code:

<View style={header}>
  <Text style={headerHint}hint</Text>
 ...
</View>

This felt quite wrong to me as it doesn't provide much value to the code, destructuring an object to grab more than 5-6 variables makes the code more difficult to read in my opinion. Also, keeping the styles in the styles object let you know your styles comes from the StyleSheet. In some cases we might want to create variables to merge several styles, they become much easier to spot.

He argues destructuring reduces areas that you need to change - if you need to change them like if the styles object changes to something else, you don't have to remove all the references to styles.

I'm wondering what is your opinion on this point and if you follow any style guide about destructuring object like this one?

\$\endgroup\$
1
  • \$\begingroup\$ It is by far the easiest way to use destructuring. Note that if not, you constantly have to refer to styles.header, styles.headerHint, ... you would have quite some work refactoring at a later point \$\endgroup\$ – Icepickle Jun 16 '17 at 8:28
3
\$\begingroup\$

I think it is a matter of preference, and also of the size of the file. If it is larger with more variables then I would tend to using the styles. prefix to disambiguate. You could also compromise and go for s = styles followed by s.headerHint.

As to the name changing issue, you could always just write styles = newGangledStyles however most decent IDEs will refactor for you and even if they don't then this type of search and replace is usually pretty straight-forward and risk free also. I also suspect that, if the styles object did change, then it would be likely that the style names would also change. Using a styles. prefix actually makes it easier to locate usages.

\$\endgroup\$
1
  • \$\begingroup\$ Also, body or button have unclear semantics without the style. prefix and the larger the scope within which those identifiers exist, the higher the chance of a collusion. \$\endgroup\$ – le_m Jun 16 '17 at 16:55

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.