1

With React Native, I'm looking to use StyleSheet to define a style and then use that style in numerous components, but I would like to change or override individual props for a few components. For example, a stack of 10 views with 5 different colors but all other props the same. Is this possible? What does the syntax look like?

I can't imagine I have to define 5 different styles or use in-line styling. Thanks very much for your help.

SunnyNonsense
  • 410
  • 3
  • 22

1 Answers1

3

You can export some globally used styles from a single module, and import them wherever you need. Then to combine styles you can use the array syntax like [ styleA, styleB ].

So in a simple example you could do something like:

// ./styles.js

import { StyleSheet } from 'react-native';

export default StyleSheet.create({
  containerDefault: {
    height: 100,
    width: 300,
    backgroundColor: 'black'
  },
  backgroundBlue: {
    backgroundColor: 'blue'
  },
  backgroundGreen: {
    backgroundColor: 'green'
  }
});

And then...

// ./SomeComponent.js

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

const ComponentBlack = () => {
  return (
    <View style={styles.containerDefault}>
      <Text>I should be black</Text>
    </View>
  );
};

const ComponentBlue = () => {
  return (
    <View style={[styles.containerDefault, styles.backgroundBlue]}>
      <Text>I should be blue</Text>
    </View>
  );
};

const ComponentGreen = () => {
  return (
    <View style={[styles.containerDefault, styles.backgroundGreen]}>
      <Text>I should be green</Text>
    </View>
  );
};

export default () => {
  return (
    <View>
      <ComponentBlack />
      <ComponentBlue />
      <ComponentGreen />
    </View>
  );
};
AndyO
  • 1,512
  • 20
  • 28
Flagship1442
  • 1,688
  • 2
  • 6
  • 13
  • 1
    Thanks, @James! Any reason to define the numerous background color overrides as you did as opposed to overriding that one property in-line? For example: – SunnyNonsense Jan 04 '20 at 03:02
  • 1
    Only really reusability, and potentially readability. You can do it inline if that makes more sense to you. But if you wanted to add more complex modifications like 3 or 4 extra style props for each component then it'll get messy doing it all inline and be cleaner handling it in the styles module. – Flagship1442 Jan 04 '20 at 03:11