Skip to content Skip to sidebar Skip to footer

How To Change Theme Color Through A Button Across App In React Native?

Hi I followed this link and implemented theme change using the Context: How to change theme color throught the Toggle in React Native? it's working fine. now want use asyncstorage

Solution 1:

If you are using a functional component you can simply go with the 'useContext' hook and get access to context.

As your requirement is to use componentDidMount you will have to go with a class contextType which will be basically a static variable in your class which points to the context.

The code would be like below, (This is based on the other question link that you have provided)

classScreenComponentOneextendsReact.Component {
    static context = Context;
    static navigationOptions = {
        headerTitle: 'First screen',
    };

    render() {
        return (
            <Viewstyle={{flex:1,
                    justifyContent: 'center',
                    backgroundColor:this.context.theme.colors.primary
                }}><Buttontitle="Go to two"onPress={() => this.props.navigation.navigate('RouteNameTwo')}
                />
                <ButtononPress={() => this.context.updateTheme(BlueGray)} title="Blue Gray Theme"></Button><ButtononPress={() => this.context.updateTheme(LightGreen)} title="Light Green Theme"></Button></View>
        )
    }
}

here 'static context = Context;' the Context would be the context that you created, it should be exported and imported to this file, but the value would be set based on the component tree.

Post a Comment for "How To Change Theme Color Through A Button Across App In React Native?"