A React Native library to easily implement dark and light themes in your app.
npm install react-native-lightdarkthemes
or
yarn add react-native-lightdarkthemes
First, wrap your root component with the ThemeProvider
from react-native-lightdarkthemes
:
import React from 'react';
import { ThemeProvider } from 'react-native-lightdarkthemes';
import App from './App';
const Root = () => {
return (
<ThemeProvider>
<App />
</ThemeProvider>
);
};
export default Root;
In your components, you can use the useTheme
hook to access the current theme and toggle between dark and light modes.
import React from 'react';
import { View, Text, Switch } from 'react-native';
import { useTheme } from 'react-native-lightdarkthemes';
const Settings = () => {
const { isDarkMode, toggleTheme } = useTheme();
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: isDarkMode ? '#000' : '#FFF' }}>
<Text style={{ color: isDarkMode ? '#FFF' : '#000' }}>
{isDarkMode ? 'Dark Mode' : 'Light Mode'}
</Text>
<Switch
trackColor={{ false: "#37B7C3", true: "#91DDCF" }}
thumbColor={isDarkMode ? "#088395" : "#f4f3f4"}
onValueChange={toggleTheme}
value={isDarkMode}
/>
</View>
);
};
export default Settings;
You can define custom styles for both dark and light modes and switch between them based on the current theme.
import React from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
import { useTheme } from 'react-native-lightdarkthemes';
const HomeScreen = () => {
const { isDarkMode, toggleTheme } = useTheme();
const styles = isDarkMode ? darkStyles : lightStyles;
return (
<View style={styles.container}>
<Text style={styles.text}>
{isDarkMode ? 'Dark Mode' : 'Light Mode'}
</Text>
</View>
);
};
const lightStyles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
text: {
fontSize: 18,
color: '#000',
},
});
const darkStyles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#000',
},
text: {
fontSize: 18,
color: '#FFF',
},
});
export default HomeScreen;
A hook to access the current theme and toggle function.
-
isDarkMode
(boolean
): Indicates whether the dark mode is active. -
toggleTheme
(function
): A function to toggle between dark and light modes.
A component to provide the theme context to your app.