$ npm install react-native-themes --save
OR
$ yarn add react-native-themes --save
//colors.jsimportThemefrom'react-native-themes';constcolors=newTheme.Colors({DEFAULT_THEME: {backgroundColor: '#fff',},DARK_THEME: {backgroundColor: '#3b5998',}});exportdefaultcolors;Note - Do not forget to import this file at the top of your component(ie. App.js).
By default the first theme in the colors template is selected. In the root component of your app like App.js, register ThemeListeners for the component to act on the default theme applied.
//App.jscomponentWillMount(){this.listener=Theme.addThemeListener(()=>{this.setState({});});}componentWillUnmount(){Theme.removeThemeListener(this.listener);}Create the stylesheet for your components as a function.
Example -
import{StyleSheet}from'react-native';conststyles=(colors)=>{returnStyleSheet.create({container: {flex: 1,justifyContent: 'center',alignItems: 'center',backgroundColor: colors.backgroundColor,},
...
});}exportdefaultstyles;In the components where you would like to apply the theme colors call the getStyles(stylesheet) function in componentWillMount().
importThemefrom'react-native-themes';importstylesheetfrom'./styles';//Stylesheet created in Step 2letstyles;classMyComponentextendsComponent{
...
componentWillMount(){styles=Theme.getStyles(stylesheet);//use the styles for styling the components in render methods.}
...
}Note
For inline styles, you can get the colors by calling Theme.getColors()
Example
render(){constcolors=Theme.getColors();return(<Viewstyle={{backgroundColor: colors.backgroundColor,flex:1}}>
...
</View>);}By default the first color theme will be applied. If you want to change the color theme you need to call the Theme.setColorTheme(themeName, callback)
themeName- Name of the theme defined in Step 1.callback- Callback function to be called after theme is set
Example-
importThemefrom'react-native-themes';
...
render(){//have to fetch styles again as the Theme Change //will re-render the Component.styles=Theme.getStyles(stylesheet);return(
...
<ButtononPress={()=>{if(Theme.getColorTheme()==='DEFAULT_THEME'){Theme.setColorTheme('DARK_THEME',()=>{this.setState({});//force re-render of the component});}else{Theme.setColorTheme('DEFAULT_THEME',()=>{this.setState({});//force re-render of the component}));}}}title="Change Theme"/>...);}Bugs? Comments? Features? PRs and Issues happily welcomed!
Sandeep Tiwari