0
\$\begingroup\$

Background: I am completely new to react-native.

Question: Is there any reason why I shouldn’t do this from an experienced point of view?

Goal: - have common styles in my react-native app? - use advantages of VSCode IntelliSense for development.

#common/styles.js

import { Platform, StyleSheet } from 'react-native';

export const styles = StyleSheet.create({
  fontFamily: {
    ...Platform.select({
      ios: {
        fontFamily: 'Baskerville',
      },
      android: {
        fontFamily: 'Noto Sans',
      },
    }),
  },
});

export const fonts = {
  h2: { fontSize: 80 },
  text: { fontSize: 12 },
};

export const BORDER_RADIUS = 5;

export const colors = {
  blue_primary: '#3F51B5',
  blue_secondary: '#E8EAF6',
  green_primary: '#73C700',
  green_secondary: '#F1F8E9',
  white: '#ffffff',
  grey_primary: '#9E9E9E',
  grey_secondary: '#FAFAFA',
  bluegrey: {
    50: '#eceff1',
    800: '#37474f',
    900: '#263238',
  },
};

Here is a plain component using this common styles:

import React from 'react';
import { View, Text } from 'react-native';
import { colors, styles, fonts } from './common/styles';

const PlainComponent = () => (
  <View style={{ flex: 1, backgroundColor: colors.bluegrey['50'] }}>
    <Text style={[fonts.h2, styles.fontFamily, { color: 'red' }]}>Hello</Text>
  </View>
);

export default PlainComponent;
\$\endgroup\$
2
\$\begingroup\$

While sharing styles is possible, I find it a little cumbersome and personally, I would not do it. Instead, I'd recommend going one level higher: do not share styles, share components.

That's what React is about - sharing components. In React Native, you won't have to import a component and styles (and pass the styles to the component), you'll just have to import the component. There will be less duplication.

I'd recommend you take a look at styled-components or glamorous-native, and see their utilities for defining styles, extending them and other utilities. They will make working with styles and components easier.

\$\endgroup\$

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.