Banner Image

Dark and Light theme using react-native/navigation

Dashrath Singh
April 27, 2022
1 Minute Read

scroll

down

Banner Image

Looking for other services or solutions?

ux/ui image
Explore our services

IN A nutshell

Dark and light theme implementation can be done according to the UI libraries using in your app, go through their docs in my case react-native-elements doesn’t have a good support of dark and light theme

IN A nutshell

To gain access to the theme in any component that is rendered inside the navigation container:, you can use the useTheme hook.

Dark and light theme implementation can be done according to the UI libraries using in your app,  go through their docs in my case react-native-elements doesn’t have a good support of dark and light theme so I am using react native navigation dark light theme functionality to set dark and light theme in my App

  • Basic theme usage in react navigation.
import * as React from 'react';
import { NavigationContainer, DefaultTheme } from '@react-navigation/native';
const MyTheme = {
 ...DefaultTheme,
 colors: {
   ...DefaultTheme.colors,
   primary: 'rgb(255, 45, 85)',
 },
};
export default function App() {
 return (
   <NavigationContainer theme={MyTheme}>{/* content */}</NavigationContainer>
 );
}
  • First of all import default theme, dark theme from react-navigation where you have wrapped your component with navigationContainer

  • Now modify the default theme and dark theme according to your App  colours for example dark theme the text should be white with 0.7 opacity and in light theme it should be black with 0.6 opacity

 you can use both methods to modify the theme object you can make a new object or modify the imported object.

  • Also import the dark mode selector in the useselector hook, We will use this selector to switch between dark and light modes
  • Now pass this theme prop in your navigation container wrapper like shown above
  •  
  • Final component for reference
  •  

Using the the light and dark theme in your custom components

  • From the docs

To gain access to the theme in any component that is rendered inside the navigation container:, you can use the useTheme hook. It returns the theme object:

import * as React from ‘react’;

import { TouchableOpacity, Text } from ‘react-native’;

import { useTheme } from ‘@react-navigation/native’;

// Black background and white text in light theme, inverted on dark theme

function MyButton() {

 const { colors } = useTheme();

 return (

   <TouchableOpacity style={{ backgroundColor: colors.card }}>

     <Text style={{ color: colors.text }}>Button!</Text>

   </TouchableOpacity>

 );

}

  • Usage Examples

Resource for reference

https://reactnavigation.org/docs/themes/

0 Shares
Tweet
Share
Share
Pin