vitalets / react-native-extended-stylesheet

Extended StyleSheets for React Native
MIT License
2.93k stars 132 forks source link

Question: Can I uncache, and re-cache just one regular noraml StyleSheet #86

Closed Noitidart closed 6 years ago

Noitidart commented 6 years ago

You have a super module here. However I didn't need all of this. I just had one StyleSheet in my entire app, I needed to use a variable in there for a color. I want to uncache it from native, re-build it. May you please show how I can do this?

vitalets commented 6 years ago

hi @Noitidart ! Could you show the code how you expect it should work?

Noitidart commented 6 years ago

Thanks so much for asking and willing to help.

I have code like this:

const COLORS = {
     primary: 'red';
}

const styles = StyleSheet.create({
    title: {
       color: COLORS.primary
    }
});

<Text style={styles.title} />
<Button onPress={this.changePrimaryColor} title="Change Primary Color" />

changePrimaryColor() {
     COLORS.primary = 'green';
     COLORS.title.color = COLORS.primary; // ideally, doing recache should read from COLORS again, but i would probably need to make this a function
     style.recache();
}
vitalets commented 6 years ago

The solution depends on the scope of color change:

  1. local - just change color in one component. Then I think the simplest way just add color dynamically to EStyleSheet styles:

    <Text style={[styles.title, {color: this.state.primaryColor}]} />

    I've made an Expo snack for that: https://snack.expo.io/B1jrweb6M

  2. If changed color is used in several parts of style, it's better to generate style dynamically but cache them as described in caching section:

    const getStyles = memoize(function(primaryColor) {
      return EStyleSheet.create({
        $primaryColor: primaryColor,
        header: {
          fontSize: '1.5rem',
          color: '$primaryColor',
          textAlign: 'center',
        },
        footer: {
          fontSize: '1rem',
          color: '$primaryColor',
          textAlign: 'left',
        },
    ...

    Example snack: https://snack.expo.io/SJAtPebpG

  3. If this is global case - you'd like to change primary color on whole app - it's better to use theming.

vitalets commented 6 years ago

Closing as the question is answered.