Skip to main content

Using themes

Knowledge of themes is required.

To provide the active theme to all React components, we'll need to render a ThemeProvider at the root of your application. By default, the active theme will automatically be detected based on a user's preference, like preferred color scheme, contrast levels, and more!

index.ts
import React from 'react';
import { AppRegistry } from 'react-native';
import { ThemeProvider } from '@aesthetic/react-native';
import './setup';
import App from './App';
function Root() {
return (
<ThemeProvider>
<App />
</ThemeProvider>
);
);
AppRegistry.registerComponent('Root', () => Root);

Only 1 ThemeProvider may be rendered in an application.

Changing themes#

As mentioned in the primary themes documentation, a theme can be changed with the changeTheme() method. When called, this method will trigger a re-render on the root ThemeProvider.

However, there is a secondary approach for changing themes, and that is through the name prop. This approach is a bit cumbersome, as it requires re-rendering the provider near the root of the application, which requires some form of state at that layer.

import { ThemeProvider } from '@aesthetic/react-native';
<ThemeProvider name="twilight">
<App />
</ThemeProvider>;

Contextual themeing#

A root ThemeProvider provides design tokens to the entire application through React context, with the active theme being automatically detected based on the device and environment (unless name is explicitly passed).

To theme a specific section of the React tree, a ContextualThemeProvider can be rendered with an explicit theme name.

import { View } from 'react-native';
import { ThemeProvider, ContextualThemeProvider } from '@aesthetic/react-native';
<ThemeProvider name="day">
<View>Inherits styles from the day theme.</View>
<ContextualThemeProvider name="night">
<View>Inherits styles from the night theme.</View>
</ContextualThemeProvider>
</ThemeProvider>;

ContextualThemeProviders can be infinitely nested, but not recommended.

Accessing the theme#

To manually access the provided Theme object, either from the root or contextually, use the useTheme() hook or withTheme() HOC.

import { useTheme } from '@aesthetic/react-native';
export default function Component() {
const theme = useTheme();
if (theme.scheme === 'dark') {
// Do something
}
return <div />;
}