Inheritance

This certainly makes it easier to write platform-specific code, but imagine having to declare the font family or indeed any base styles for each platform everywhere we want to use a Text component in our application. For web developers who are used to the inheritance pattern of CSS, this kind of repetition just won’t do.

Fortunately, we can recreate a different sort of inheritance pattern for styles using JavaScript. For our projects, we create a common directory inside the main js directory. This folder houses commonly-reused components throughout the app. For example, we can declare common Text and Header components like so:
/*
 * @providesModule CommonText
 */
import React from 'react';
import ReactNative from 'react-native';
import PlatformStyleSheet from 'PlatformStyleSheet';


const styles = PlatformStyleSheet.create({
  font: {
    ios: {
      fontFamily: ‘Arial’,
    },
    android: {
      fontFamily: ‘Roboto’,
    },
  },
  h2: {
    fontWeight: '700',
    lineHeight: 26,
    fontSize: 20,
  },
});
 
 
export const Text = ({ style, ...props }) =>
  <ReactNative.Text style={[styles.font, style]} {...props} />;
 
 
export const H2 = ({ style, ...props }) =>
  <ReactNative.Text style={[styles.font, styles.h2, style]} {...props} />;
Here we are importing the base Text component from React Native and applying some base styles that will be inherited wherever this common Text component is imported elsewhere in the app. This also allows us to declare those heading tags that we all know and love from the web. Using the ProvidesModule again, we can simply import these common text components rather than the React Native defaults.
import { Text, H2 } from ‘CommonText’;
We can still apply custom styles to these components, but no longer do we have to declare font family over and over. This pattern is also extendable to other commonly-used components. Anywhere you find yourself redeclaring base styles in multiple locations is a good place to pause and refactor a base component for reuse throughout the app. This makes code maintenance much easier since any changes to base styles can now be done through a single component, rather than throughout the codebase. For example, that Touchable Opacity button that keeps being rewritten over and over might better serve as a Button component imported from the common directory.

Comments

Popular posts from this blog

Platform Styles