Using Theme
UI Kitten provides hooks and a higher-order component for accessing the current Eva theme and creating theme-aware stylesheets.
Import
import { useTheme, useStyleSheet, withStyles } from '@ui-kitten/components';
useTheme
Returns the current Eva theme object containing all design tokens (colors, spacing, etc.).
import React from 'react';
import { View } from 'react-native';
import { useTheme } from '@ui-kitten/components';
const ThemedComponent = () => {
const theme = useTheme();
return (
<View style={{ backgroundColor: theme['background-basic-color-1'] }} />
);
};
Typed tokens
The theme object is typed with the token names of the bundled design systems, so the editor suggests
theme['color-primary-500'] and the useThemeValue selector argument, and a typo in a known token is
still a plain string lookup rather than an error. Custom tokens keep working through the string
index signature. @ui-kitten/eva exports EvaThemeKey / EvaTheme and @ui-kitten/material exports
MaterialThemeKey / MaterialTheme; @ui-kitten/components exports KnownThemeKey (the union of both)
and ThemeKey (KnownThemeKey | string).
import type { EvaThemeKey } from '@ui-kitten/eva';
import type { ThemeKey } from '@ui-kitten/components';
const accent: EvaThemeKey = 'color-primary-500';
const custom: ThemeKey = 'my-brand-color';
useStyleSheet
Creates a memoized stylesheet that recalculates when the theme changes.
import React from 'react';
import { View, Text } from 'react-native';
import { useStyleSheet, useTheme } from '@ui-kitten/components';
const ThemedComponent = () => {
const styles = useStyleSheet(themedStyles);
return (
<View style={styles.container}>
<Text style={styles.text}>Themed Text</Text>
</View>
);
};
const themedStyles = (theme) => ({
container: {
backgroundColor: theme['background-basic-color-1'],
},
text: {
color: theme['text-basic-color'],
},
});
withStyles
A higher-order component alternative to the hooks. Injects eva.theme and eva.style into the wrapped component.
import React from 'react';
import { View, Text } from 'react-native';
import { withStyles } from '@ui-kitten/components';
const MyComponent = ({ eva }) => (
<View style={eva.style.container}>
<Text style={eva.style.text}>Themed Text</Text>
</View>
);
export default withStyles(MyComponent, (theme) => ({
container: {
backgroundColor: theme['background-basic-color-1'],
},
text: {
color: theme['text-basic-color'],
},
}));
API
| Export | Type | Description |
|---|---|---|
useTheme | () => ThemeType | Hook returning the current Eva theme object. |
useStyleSheet | (themeStyleFactory) => StyleSheet | Hook returning a memoized stylesheet derived from the theme. |
withStyles | (Component, createStyles?) => Component | HOC injecting theme and computed styles via eva prop. |
Storybook
Live examples coming soon via Storybook.