Skip to content

Instantly share code, notes, and snippets.

@dantman
Last active March 23, 2018 07:04
Show Gist options
  • Save dantman/8fcbb087ee3935d711e15bb0cce0ac17 to your computer and use it in GitHub Desktop.
Save dantman/8fcbb087ee3935d711e15bb0cce0ac17 to your computer and use it in GitHub Desktop.
React Native `@Styles` decorator
import React, {PureComponent} from 'react';
import {View} from 'react-native';
import Styles from './Styles';
@Styles({
root: {
// ...
},
})
export default class Example extends PureComponent {
render() {
const {styles} = this;
return (
<View style={styles.root}>
{/* ... */}
</View>
);
}
}

The @Styles decorator can be used as a decorator for a react component class. The decorator creates a react-native StyleSheet (using StyleSheet.create) and assigns it to the class' prototype with the name styles.

This eliminates the need for an external styles variable (allowing multiple components to be present in the same class with separate styles). But also ensures that only one StyleSheet instance is created per-class and does not leak memory (as doing styles = StyleSheet.create(...); within the class itself would do).

@Styles({
  // ...
})
class Example extends PureComponent
'use strict';
import {StyleSheet} from 'react-native';
export default function(styles) {
return function(Component) {
Object.defineProperty(Component.prototype, 'styles', {
enumerable: false,
value: StyleSheet.create(styles)
});
return Component;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment