// define named styles using defined theme variables
vars=>({
container:{
padding:40,
backgroundColor:vars.color.primary
},
button:{
borderWidth:vars.border.thick,
backgroundColor:vars.color.secondary
}
})
)
Create another theme from Default Theme / child theme (optional)
exportconstRedTheme=BlueTheme.extend(
// override default theme variables
{
color:{
primary:'red',
secondary:'green'
}
},
// override default theme style
vars=>({
container:{
padding:80
},
button:{
borderWidth:vars.border.bold
}
})
)
Create Theme Context
import{ThemeContext}from'anoa-react-native-theme'
exportconstAppTheme=newThemeContext(BlueTheme,{
red:RedTheme
// define the rest themes you have, eg:
// green: GreenTheme,
// yellow: YellowTheme
// etc ...
// Notice: all themes defined here must created/extended
// from default theme or child of default theme.
})
Theme Provider
We are using React Context to provide themes accessibility.
The AppTheme you've created above contains Provider and Consumer property.
You have to wrap your root component with Provider to make themes
available in every component inside.
exportdefaultclassAppextendsComponent{
// ...
render(){
return(
<AppTheme.Provider
// optional prop to get default theme
getDefault={async()=>{
// do async operation to get selected theme
// should returns 'default' or the object key of themes
// you've defined in the context (eg: 'red' for RedTheme)
returnawaitMyFancyStorage.getTheme()
}}
// optional prop, the event that listen when theme get changed
onChange={asynckey=>{
// key returns the 'default' or the object key of themes
awaitMyFancyStorage.setTheme(key)
}}
>
<Viewstyle={styles.container}>
<AwesomeComponent/>
</View>
</AppTheme.Provider>
)
}
// ...
}
Consuming Theme
To consume theme you need to wrap the component with Consumer. Wrapping with Consumer can also be done by using withTheme HOC or withThemeClass class decorator.
Consume theme using AppTheme.Consumer
The Consumer resulting function component with one parameter called theme consists of:
vars -- represents current theme variables.
styles -- represents current theme named stylesheets.