Consuming Themes
This section show how to consume (use) theme colors for your components. For more details about React Context or how to consume React Context please read this link.
import React from 'react';
import { Text } from 'react-native';
import ThemeContext from '@flexnative/theme-context';
export default class extends React.Component {
render() {
return (
<ThemeContext.Consumer>
{value => <Text>
{ JSON.stringify(value, null, 2) }
</Text>}
</ThemeContext.Consumer>
);
}
}
Ore you can use the useThemeContext
hook to consume the theme.
- Function Component
- Class Component
import { Pressable, StyleSheet, Text } from 'react-native';
import { useThemeContext } from '@flexnative/theme-context';
const ThemedButton = React.memo((props) => {
const theme = useThemeContext();
return (
<Pressable style={({pressed}) => [styles.wrapperCustom, { backgroundColor: pressed ? theme.dark : theme.primary }]}>
<Text style={styles.text}>{props.text}</Text>
</Pressable>
);
});
const styles = StyleSheet.create({
text: {
fontSize: 16,
},
wrapperCustom: {
borderRadius: 8,
padding: 6,
}
});
import React from 'react';
import { Pressable, StyleSheet, Text } from 'react-native';
import ThemeContext from '@flexnative/theme-context';
class ThemedButton extends React.Component {
static contextType = ThemeContext;
declare context: React.ContextType<typeof ThemeContext>;
render() {
return (
<Pressable style={({pressed}) =>
[styles.wrapperCustom, { backgroundColor: pressed ? this.context.colors.dark : this.context.colors.primary }]}>
<Text style={styles.text}>{props.text}</Text>
</Pressable>
);
}
}
const styles = StyleSheet.create({
text: {
fontSize: 16,
},
wrapperCustom: {
borderRadius: 8,
padding: 6,
}
});