Search code examples
reactjsreact-nativereact-native-ui-kitten

Theming for React Native using react native ui kitten


I am trying to use the react-native-ui-kitten for react native components and its working great. Lately I wanted to add theming in my app and to do that I used their 'RkTheme' and 'RkType' but none is working.

Expectation - setting the theme using RkTheme.setTheme(themeJson) should change the styling of elements already rendered on the screen

Actual - setting the theme using RkTheme.setTheme(themeJson) is not changing the style of the already rendered componenets.

Below is a part of package json

  "dependencies": {
"prop-types": "^15.6.1",
"react": "16.2.0",
"react-dom": "^16.3.1",
"react-native": "0.51.0",
"react-native-linear-gradient": "^2.4.0",
"react-native-popup-menu": "^0.9",
"react-native-ui-kitten": "3.1.2",
"react-native-vector-icons": "^4.6.0",
"react-navigation": "1.0.0-beta.11",
"react-redux": "^5.0.7",
"realm": "^2.15.3",
"redux": "^3.7.2",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0",
"util": "^0.11.0",

},

Sample code for the react component

    import React from 'react'
import { StyleSheet, Text, View, Image, Button , TouchableOpacity} from 'react-native'
import {applyTheme} from '../config/bootstrap'
import {RkStyleSheet, RkTheme} from 'react-native-ui-kitten'
import { LightTheme } from '../config/lightTheme';
import { DarkTheme } from '../config/darkTheme';
export default class Sample extends React.Component {
  constructor(props){
    super(props)
    this.changeTheme = this.changeTheme.bind(this)
  }
  changeTheme(theme){
    if(theme){
      RkTheme.setTheme(DarkTheme,null)
    } else {
      RkTheme.setTheme(LightTheme,null)
    }
  }
  render() {
    return (
      <View style={styles.container}>
        <Text>Sample</Text>
        <TouchableOpacity  onPress = { (e) => this.changeTheme(false) }>
          <Text style={styles2.button1}>Apply Light</Text>
        </TouchableOpacity>
        <TouchableOpacity   onPress = { (e) => this.changeTheme(true) }>
          <Text style={styles2.button1}>Apply Dark</Text>
        </TouchableOpacity>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
})
const styles2 = RkStyleSheet.create(theme => ({
  button1 : {
    color : theme.colors.secondaryColor
  }
}))

Solution

  • We need to add 'withRkTheme' to the components that we suppose will change the theme colors in real time after changing theme. Also important point to note is that if we are using any other custom components in the render function of the root component, the custom components should extend 'RkComponent' instead of 'React.Component'. This Alone fixed my issue.