React Native Elements Global Styling

Viewed 1213

Instead of styling each element individually, let's say background color of many elements on different pages / components in my react native apps...

What is the best practice of the global styling for the common elements? The efficient way. Thanks guys.

PS : I'm using function instead of class and I'm new to this react-native thing.

2 Answers

If you dont want to use class inheritance, you can write HOC which can apply styles to its child. Inside the child component, inherit required property styles from parent. BaseStyle is the hoc, maintaining the css definitions for all components. On your component that needs to inherit, we need to wrap them with the BaseStyle by providing the required style prop.

function ComponentInheritingStyle() {
  return (
      <BaseStyle style={styles.button}>
          {...this.props.children}
     </BaseStyle>
     );
   }

export const styles = StyleSheet.create({
  button: {
    backgroundColor: 'blue',
    fontSize: '12',
    borderRadius: '4',
  },
  div: {
    border: '2px',
    borderColor: 'lightblue',
    padding: 10,
    marginBottom: 10
  }
})

you could read the below link for better clarity, through class. Inheritance in React JS

React native styling is based on js objects. So, you could create your "styling" objects on separate js files and import those files into your react components. Since sometimes it is a good idea to change the style of an object based on the values of a state variable then it could be great to have the needed values nearby for "fast understanding". All depends on how you organize your code. For example, the next code (from native tutorial) can be declared on a separate js file:

export const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
      },
      button: {
        alignItems: 'center',
        backgroundColor: '#DDDDDD',
        padding: 10,
        marginBottom: 10
      }
    })

and later import using an import command:

import {styles} from '.... path to file where you placed styles code ... "
Related