Hi Guys, In this article we are going to learn How to add dynamic theme in React Native, Now days mobile application need to have dynamically change style as per requirement. to implement this we’ll have to implement context api to share between parent to child. We can pass style as well as function through context API. so let’s understand with an example.
1. Create base theme
First, create new file for your base theme. for example, StyleContext.js
import React, { createContext, useState } from 'react';
// Define the context
export const StyleContext = createContext();
const darkTheme = {
textColor: '#ffffff',
backgroundColor: '#000000',
};
// Define light and dark themes
const lightTheme = {
textColor: '#000000',
backgroundColor: '#ffffff',
};
// Create a provider component
export const StyleProvider = ({ children }) => {
const [theme, setTheme] = useState(lightTheme);
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === lightTheme ? darkTheme : lightTheme));
};
return (
<StyleContext.Provider value={{ theme, toggleTheme }}>
{children}
</StyleContext.Provider>
);
};
2. Wrap your main application with the StyleProvider
In your main App.js file, wrap your application with the StyleProvider.
import React from 'react';
import { StyleProvider } from './StyleContext';
import MyComponent from './MyComponent';
const App = () => {
return (
<StyleProvider>
<MyComponent />
</StyleProvider>
);
};
export default App;
3. Use Style Context in your Components
In your components, you can now use the Style context to apply styles dynamically.
import React, { useContext } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { StyleContext } from './StyleContext';
const MyComponent = () => {
const { theme, toggleTheme } = useContext(StyleContext);
return (
<View style={[styles.container, { backgroundColor: theme.backgroundColor }]}>
<Text style={{ color: theme.textColor }}>Hello, World!</Text>
<Button title="Toggle Theme" onPress={toggleTheme} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default MyComponent;
- Create a Context:
StyleContextto hold style theme related data. - Create a Provider:
StyleProviderto manage and provide the theme state. - Wrap your application: with the
StyleProviderin your main app component. - Consume the Context: Use in your components to dynamically change styles based on the current theme.
Thank you

Apni website ka SSL badal le lodu
Done