Implementing Dark mode: React native app

Gaurav Kumar
2 min readMar 21, 2023

--

Source: Google image

Dark mode is a cool feature to have in mobile apps. Here is a step by step guideline to implement it in a React native app.

  1. Set up a theme file: Create a file named theme.js in your app's root directory. In this file, you can define your app's color scheme for both light and dark mode.

Theme.js

export const lightTheme = {
backgroundColor: '#FFFFFF',
textColor: '#000000',
};
export const darkTheme = {
backgroundColor: '#000000',
textColor: '#FFFFFF',
};

2. Create a Context: Create a ThemeContext using the React createContext API. This context will provide the theme to all the components in your app.

themeContext.js

import React, { createContext, useState } from 'react';
import { lightTheme, darkTheme } from './theme';
export const ThemeContext = createContext();export const ThemeProvider = ({ children }) => {
const [isDarkMode, setIsDarkMode] = useState(false);
const theme = isDarkMode ? darkTheme : lightTheme;
return (
<ThemeContext.Provider value={{ theme, isDarkMode, setIsDarkMode }}>
{children}
</ThemeContext.Provider>
);
};

3. Use the context in your components: Wrap your top-level component in the ThemeProvider component. This will make the theme available to all the child components.

App.js

import { ThemeProvider } from './themeContext';
const App = () => {
return (
<ThemeProvider>
<MyComponent />
</ThemeProvider>
);
};

4. Toggle the theme: Create a button or switch in your app to toggle the theme. You can use the setIsDarkMode function from the ThemeContext to toggle the theme.

import { useContext } from 'react';
import { ThemeContext } from './themeContext';
const ToggleButton = () => {
const { isDarkMode, setIsDarkMode } = useContext(ThemeContext);
const handleToggle = () => {
setIsDarkMode(!isDarkMode);
};
return (
<Button onPress={handleToggle}>
{isDarkMode ? 'Switch to Light Mode' : 'Switch to Dark Mode'}
</Button>
);
};

5. Use the theme in your components: You can use the theme object from the ThemeContext to style your components based on the current theme.

import { useContext } from 'react';
import { ThemeContext } from './themeContext';
const MyComponent = () => {
const { theme } = useContext(ThemeContext);
return (
<View style={{ backgroundColor: theme.backgroundColor }}>
<Text style={{ color: theme.textColor }}>Hello, World!</Text>
</View>
);
};

That’s it! You have completed dark mode implementation.

--

--

Gaurav Kumar
Gaurav Kumar

No responses yet