Certainly! To incorporate these additional themes into your React Native application, we'll need to modify your ThemeContext to support multiple custom themes beyond just the light and dark modes.
Here's how you can do it:
1. Define the Additional Themes
First, we'll create new theme objects for each of the themes you've provided: Deep Navy & Gold, Black & Platinum, Emerald Green & Gold, and Charcoal & Rose Gold.
// context/ThemeContext.js
// ... existing imports
// Define the additional themes
const NavyGoldTheme = {
...CombinedDefaultTheme,
dark: false,
colors: {
...CombinedDefaultTheme.colors,
primary: '#001F3F', // Navy Blue
accent: '#D4AF37', // Gold
background: '#FFFFFF', // White
surface: '#FFFFFF', // White Surface
text: '#001F3F', // Navy Blue Text
placeholder: '#7F8C8D', // Gray Placeholder Text
error: '#E74C3C', // Red for Errors
onSurface: '#001F3F', // Navy Blue on Surface
disabled: '#BDC3C7', // Light Gray for Disabled Elements
backdrop: '#FFFFFF', // White Backdrop
border: '#D4AF37', // Gold Border
textSecondary: '#7F8C8D', // Gray Secondary Text
success: '#2ECC71', // Green for Success Messages
info: '#3498DB', // Blue for Informational Messages
},
};
const BlackPlatinumTheme = {
...CombinedDarkTheme,
dark: true,
colors: {
...CombinedDarkTheme.colors,
primary: '#1C1C1C', // Matte Black
accent: '#E5E4E2', // Platinum Silver
background: '#1C1C1C', // Matte Black
surface: '#F2F2F2', // Soft Gray Surface
text: '#E5E4E2', // Platinum Silver Text
placeholder: '#AAAAAA', // Light Gray Placeholder Text
error: '#E74C3C', // Red for Errors
onSurface: '#E5E4E2', // Platinum Silver on Surface
disabled: '#3E3E3E', // Dark Gray for Disabled Elements
backdrop: '#000000', // Black Backdrop
border: '#E5E4E2', // Platinum Silver Border
textSecondary: '#CCCCCC', // Light Gray Secondary Text
success: '#2ECC71', // Green for Success Messages
info: '#3498DB', // Blue for Informational Messages
},
};
const EmeraldGoldTheme = {
...CombinedDefaultTheme,
dark: false,
colors: {
...CombinedDefaultTheme.colors,
primary: '#046307', // Emerald Green
accent: '#D4AF37', // Gold
background: '#FFFFFF', // White
surface: '#FFFFFF', // White Surface
text: '#046307', // Emerald Green Text
placeholder: '#95A5A6', // Gray Placeholder Text
error: '#E74C3C', // Red for Errors
onSurface: '#046307', // Emerald Green on Surface
disabled: '#D0D0D0', // Light Gray for Disabled Elements
backdrop: '#FFFFFF', // White Backdrop
border: '#333333', // Charcoal Gray Border
textSecondary: '#7F8C8D', // Gray Secondary Text
success: '#2ECC71', // Green for Success Messages
info: '#3498DB', // Blue for Informational Messages
},
};
const CharcoalRoseGoldTheme = {
...CombinedDarkTheme,
dark: true,
colors: {
...CombinedDarkTheme.colors,
primary: '#2F2F2F', // Charcoal Gray
accent: '#B76E79', // Rose Gold
background: '#2F2F2F', // Charcoal Gray
surface: '#FAF3E3', // Soft Ivory Surface
text: '#FAF3E3', // Soft Ivory Text
placeholder: '#CCCCCC', // Light Gray Placeholder Text
error: '#E74C3C', // Red for Errors
onSurface: '#FAF3E3', // Soft Ivory on Surface
disabled: '#555555', // Dark Gray for Disabled Elements
backdrop: '#000000', // Black Backdrop
border: '#B76E79', // Rose Gold Border
textSecondary: '#BBBBBB', // Light Gray Secondary Text
success: '#2ECC71', // Green for Success Messages
info: '#3498DB', // Blue for Informational Messages
},
};
2. Update the ThemeContext
We'll modify your ThemeContext to support these multiple themes. We'll introduce a new state variable themeName to keep track of the current theme's name, which will be helpful when switching themes.
// context/ThemeContext.js
import React, { createContext, useState, useEffect } from 'react';
import { Appearance } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import merge from 'deepmerge';
import { DarkTheme as PaperDarkTheme, DefaultTheme as PaperDefaultTheme } from 'react-native-paper';
import { DarkTheme as NavigationDarkTheme, DefaultTheme as NavigationDefaultTheme } from '@react-navigation/native';
// Define cache key for AsyncStorage
const THEME_PREFERENCE_KEY = 'userThemePreference';
// Merge Paper and Navigation themes for Dark and Default
const CombinedDarkTheme = merge(PaperDarkTheme, NavigationDarkTheme);
const CombinedDefaultTheme = merge(PaperDefaultTheme, NavigationDefaultTheme);
// Existing Customized Themes
// ... (CustomizedDarkTheme and CustomizedDefaultTheme definitions)
// Include the new themes
// ... (NavyGoldTheme, BlackPlatinumTheme, EmeraldGoldTheme, CharcoalRoseGoldTheme definitions)
// Define the available themes
const themes = {
light: CustomizedDefaultTheme,
dark: CustomizedDarkTheme,
navyGold: NavyGoldTheme,
blackPlatinum: BlackPlatinumTheme,
emeraldGold: EmeraldGoldTheme,
charcoalRoseGold: CharcoalRoseGoldTheme,
};
// Create the ThemeContext with default values
export const ThemeContext = createContext({
theme: CustomizedDefaultTheme,
themeName: 'light',
setThemeByName: () => {},
});
export const ThemeProvider = ({ children }) => {
const [themeName, setThemeName] = useState('light');
const [theme, setTheme] = useState(themes[themeName]);
useEffect(() => {
// Load theme preference from AsyncStorage on mount
const loadThemePreference = async () => {
try {
const storedThemeName = await AsyncStorage.getItem(THEME_PREFERENCE_KEY);
if (storedThemeName && themes[storedThemeName]) {
setThemeName(storedThemeName);
setTheme(themes[storedThemeName]);
} else {
// If no preference is stored, set theme based on system preference
const colorScheme = Appearance.getColorScheme();
const defaultThemeName = colorScheme === 'dark' ? 'dark' : 'light';
setThemeName(defaultThemeName);
setTheme(themes[defaultThemeName]);
}
} catch (error) {
console.error('Failed to load theme preference:', error);
}
};
loadThemePreference();
// Listen to system theme changes
const subscription = Appearance.addChangeListener(({ colorScheme }) => {
// Only change theme if user hasn't set a preference
AsyncStorage.getItem(THEME_PREFERENCE_KEY)
.then((storedThemeName) => {
if (!storedThemeName) {
const newThemeName = colorScheme === 'dark' ? 'dark' : 'light';
setThemeName(newThemeName);
setTheme(themes[newThemeName]);
}
})
.catch((error) => {
console.error('Failed to get theme preference:', error);
});
});
return () => {
subscription.remove();
};
}, []);
const setThemeByName = async (selectedThemeName) => {
try {
if (themes[selectedThemeName]) {
setThemeName(selectedThemeName);
setTheme(themes[selectedThemeName]);
await AsyncStorage.setItem(THEME_PREFERENCE_KEY, selectedThemeName);
} else {
console.warn(`Theme '${selectedThemeName}' does not exist.`);
}
} catch (error) {
console.error('Failed to set theme:', error);
}
};
return (
<ThemeContext.Provider value={{ theme, themeName, setThemeByName }}>
{children}
</ThemeContext.Provider>
);
};
3. Update Your Components to Use the New Themes
In your components, you can now use the ThemeContext to apply the theme and provide options for the user to switch themes.
// ExampleComponent.js
import React, { useContext } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import { ThemeContext } from './context/ThemeContext';
const ExampleComponent = () => {
const { theme, themeName, setThemeByName } = useContext(ThemeContext);
const themesList = [
{ name: 'Light', key: 'light' },
{ name: 'Dark', key: 'dark' },
{ name: 'Deep Navy & Gold', key: 'navyGold' },
{ name: 'Black & Platinum', key: 'blackPlatinum' },
{ name: 'Emerald Green & Gold', key: 'emeraldGold' },
{ name: 'Charcoal & Rose Gold', key: 'charcoalRoseGold' },
];
return (
<View style={[styles.container, { backgroundColor: theme.colors.background }]}>
<Text style={[styles.title, { color: theme.colors.text }]}>Current Theme: {themeName}</Text>
{themesList.map((item) => (
<TouchableOpacity
key={item.key}
style={[styles.button, { backgroundColor: theme.colors.primary }]}
onPress={() => setThemeByName(item.key)}
>
<Text style={[styles.buttonText, { color: theme.colors.onSurface }]}>{item.name}</Text>
</TouchableOpacity>
))}
</View>
);
};
export default ExampleComponent;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
padding: 16,
},
title: {
fontSize: 24,
marginVertical: 16,
},
button: {
width: '100%',
padding: 12,
marginVertical: 8,
borderRadius: 8,
alignItems: 'center',
},
buttonText: {
fontSize: 18,
},
});
4. Wrap Your App with the ThemeProvider
Ensure that your app is wrapped with the ThemeProvider in your main entry point so that all components have access to the theme context.
// App.js
import React, { useContext } from 'react';
import { ThemeProvider, ThemeContext } from './context/ThemeContext';
import { Provider as PaperProvider } from 'react-native-paper';
import { NavigationContainer } from '@react-navigation/native';
import ExampleComponent from './ExampleComponent';
const App = () => {
return (
<ThemeProvider>
<ThemeContext.Consumer>
{({ theme }) => (
<PaperProvider theme={theme}>
<NavigationContainer theme={theme}>
<ExampleComponent />
</NavigationContainer>
</PaperProvider>
)}
</ThemeContext.Consumer>
</ThemeProvider>
);
};
export default App;
5. Customize Other Colors as Needed
In the theme definitions, make sure to define all the necessary colors used in your app, such as error, placeholder, border, textSecondary, etc., utilizing the new color schemes.
For example, in NavyGoldTheme, we've defined border as Gold and textSecondary as Gray.
6. Handle Undefined Themes
In the setThemeByName function within your ThemeContext, we check if the provided selectedThemeName exists in the themes object to prevent errors.
const setThemeByName = async (selectedThemeName) => {
try {
if (themes[selectedThemeName]) {
setThemeName(selectedThemeName);
setTheme(themes[selectedThemeName]);
await AsyncStorage.setItem(THEME_PREFERENCE_KEY, selectedThemeName);
} else {
console.warn(`Theme '${selectedThemeName}' does not exist.`);
}
} catch (error) {
console.error('Failed to set theme:', error);
}
};
7. Test Each Theme
After implementing the themes, make sure to test each one thoroughly to ensure that all UI elements display correctly and cohesively with the new color schemes.
Additional Notes
- AsyncStorage is used to persist the user's theme preference across app sessions.
- themeName holds the current theme's name, which is helpful for displaying the current theme and debugging.
- setThemeByName allows you to switch themes programmatically by theme name.
Example Usage in Your App
With these changes, your app will now support multiple custom themes, and users can switch between them. You can enhance the user experience by adding theme selection in your app's settings or theme picker component.
If you have any questions or need further assistance with implementing the themes, feel free to ask!