What does StyleSheet.create do and why is it useful?

Technology CommunityCategory: React NativeWhat does StyleSheet.create do and why is it useful?
VietMX Staff asked 3 years ago

StyleSheet is an abstraction similar to CSS StyleSheets. StyleSheet.create creates a StyleSheet style reference from the given object.

const styles = StyleSheet.create({
  container: {
    borderRadius: 4,
    borderWidth: 0.5,
    borderColor: '#d6d7da',
  },
  title: {
    fontSize: 19,
    fontWeight: 'bold',
  },
  activeTitle: {
    color: 'red',
  },
});

Use a StyleSheet:

<View style={styles.container}>
  <Text style={[styles.title, this.props.isActive && styles.activeTitle]} />
</View>

StyleSheet are useful because:

  • By moving styles away from the render function, you’re making the code easier to understand.
  • Naming the styles is a good way to add meaning to the low level components in the render function.