React Native StyleSheets Global Design Constants

81 Views Asked by At

I am wondering if there was some way to setup global design constants to use in React Native Stylesheets.

When I used styled components I was able to set-up something like

TextInput.tsx

import React from 'react';
import {TextInputProps} from 'react-native';
import {Label} from './TextInputStyle';

interface ITextInputProps extends TextInputProps {
  label?: string;
}

const TextInput = ({label}: ITextInputProps) => {
  return (
      <Label>{label}</Label>
  );
};

export default TextInput;

TextInputStyle.ts

export const Label = styled.Text`
  ${Body};
  align-self: flex-end;
`;

typography.ts

export const Body = css`
  font-family: 'Rubik-Regular';
  font-size: 16px;
  line-height: 22px;
  color: ${DarkGrey2};
`;

I created this Body style as a global constant that I could use accross my styled components. I was wondering if I could do something like that with my React Natvie Stylesheets.

Instead of doing something like this:

const styles = StyleSheet.create({
  root: {
    display: 'flex',
    flexDirection: 'row',
    paddingVertical: 21,
    textAlign: 'center',
    alignItems: 'center',
  },
});

I could do this

const styles = StyleSheet.create({
  root: {
   ${flexCenterRow}
    paddingVertical: 21,
  },
});

globalstyles.ts

export const flexCenterRow = {
    display: 'flex',
    flexDirection: 'row',
    textAlign: 'center',
    alignItems: 'center',
}
1

There are 1 best solutions below

0
Vlasta Řenčová On

I think you could achieve global design constants in React Native by creating a separate file for your global styles (which you already did), and then importing and using these styles across your components. Here's the idea:

Create a Global Styles File:

// globalStyles.ts
export const flexCenterRow = {
  display: 'flex',
  flexDirection: 'row',
  textAlign: 'center',
  alignItems: 'center',
};

Then import the global styles where you want to use them:

// TheComponent.ts
import React from 'react';
import { StyleSheet, View } from 'react-native';
import { flexCenterRow } from './globalStyles';

const styles = StyleSheet.create({
  root: {
    ...flexCenterRow,
    paddingVertical: 21,
  },
});

const YourComponent = () => {
  return (
    <View style={styles.root}>
      {/* Your component code */}
    </View>
  );
};

export default TheComponent;

In the styles object, we can use the spread operator (...) to merge the properties of flexCenterRow from your globalStyles.ts file into your component's specific style object.