Amir Panahandeh
Amir Panahandeh

Reputation: 9029

Change whole application theme based on a state React Native

I'm trying to create an application which user can change primary color and for that I've created this class

const mode = true;

export default class Colors {
    static primary() {
        return mode ? '#fff' : '#000';
    }

    static accent() {
        return mode ? '#fff' : '#000';
    }
}

and in Components

const styles = StyleSheet.create({
    header: {
        height: 100,
        backgroundColor: Colors.primary()
    }
});

so when user clicks on changing the theme the mode will change. The problem is how can I force all Components and Pages to refresh and use the new styles when the mode changes?

Upvotes: 0

Views: 2400

Answers (3)

Yash Ojha
Yash Ojha

Reputation: 818

I don't know if you like using global variables or not. But they can really help you here, you don't need a state. Just create some global variables in your index.js such as

global.themeColorDark = "rgb(0,106,176)";
global.themeColorLight = "rgb(10,143,192)";
global.themeColorBackground = "white";

and then, you can access and edit these variables from anywhere in your app. without importing any file.

Upvotes: 1

Anand Neema
Anand Neema

Reputation: 670

Read This:

https://medium.com/@jonlebensold/getting-started-with-react-native-redux-2b01408c0053

then you can access state on any Screen of page via mapStateToProp.

But if you want to store to store theme permanently then you have to store in userDefault

    import React , {PureComponent} from 'react';
    import {
      View,
      Text,
      } from 'react-native';
    import { connect } from 'react-redux';
    import { bindActionCreators } from 'redux';

    const mapStateToProps = (() => {
      return {
        colorStyle: colorTheme.style,
      };
    });

    class ColorTheme extends PureComponent {

      constructor(props) {
        super(props);
      }

      render() {
          console.log(this.props.colorStyle)
      }

    }

    export default connect(mapStateToProps, null)(ColorTheme);

Upvotes: 0

Muhammed Mirza
Muhammed Mirza

Reputation: 126

If you are using redux(or something like that)

  • Define a variable in reducer
  • Bind mapStateToProps function to component
  • Then change that variable in reducer when you want

Upvotes: 0

Related Questions