Home » React-native » How to add dynamic theme in React Native

How to add dynamic theme in React Native

Pro Level React-native
How to add dynamic theme in React Native

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: StyleContext to hold style theme related data.
  • Create a Provider: StyleProvider to manage and provide the theme state.
  • Wrap your application: with the StyleProvider in your main app component.
  • Consume the Context: Use in your components to dynamically change styles based on the current theme.

Thank you

Related Posts

2 thoughts on “How to add dynamic theme in React Native

Leave a Reply

Your email address will not be published. Required fields are marked *