Skip to main content
Version: 0.1.5

Theme Related Functions and Hook

Functions

toggleTheme()

The toggleTheme() function allows you to programmatically toggle the theme of your application between 'dark' and ' light' modes. This function can be easily imported from the react-native-smart-styles module and used within your application to enhance the user experience by providing theme-switching capabilities.

Importing and Usage

You can import and use toggleTheme() as follows:

import { toggleTheme } from 'react-native-smart-styles';
// Toggle between 'dark' and 'light' theme
toggleTheme();

Example

Here's an example of how you might use toggleTheme() in a button click handler to allow users to switch themes:

import React from 'react';
import { Button } from 'react-native';
import { toggleTheme } from 'react-native-smart-styles';

const ThemeToggleButton = () => {
return (
<Button
title="Toggle Theme"
onPress={() => toggleTheme()}
/>
);
};

export default ThemeToggleButton;

This function is particularly useful in apps where users might prefer different themes under different conditions ( e.g., darker themes at night).


getTheme()

The getTheme() function allows you to retrieve the currently active theme within your application, enabling you to make conditional decisions based on whether the theme is set to 'dark' or 'light'. This function can be imported from the react-native-smart-styles module.

Importing and Usage

You can import and use getTheme() as follows:

import { getTheme } from 'react-native-smart-styles';

// Retrieve the current theme
const currentTheme = getTheme();
console.log(currentTheme); // Outputs: 'dark' or 'light'

Example

Here's an example of how you might use getTheme() to conditionally apply styles based on the current theme:

import React from 'react';
import { Text, View } from 'react-native';
import { getTheme } from 'react-native-smart-styles';

const ThemedText = () => {
const theme = getTheme();
const textStyle = {
color: theme === 'dark' ? '#FFF' : '#000',
backgroundColor: theme === 'dark' ? '#333' : '#CCC',
};

return (
<View style={{ padding: 20 }}>
<Text style={textStyle}>This text style changes with the theme!</Text>
</View>
);
};

export default ThemedText;

This method is especially useful for applications that need to dynamically adjust their appearance based on the current theme settings, enhancing the user interface's adaptability and responsiveness.


themeColor / tc

themeColor(lightColor, darkColor) / tc(lightColor, darkColor)

These functions dynamically specify colors based on the active color scheme and must be used within SmartStyles.create() or SmartStyles.helper() to ensure proper functionality. Both themeColor and tc perform the same operation and can be used interchangeably.

warning

If called inside SmartStyles.create() it will be executed once and won't consider theme changes

info

In order to use properly must be used inside SmartStyles.helper() and passed to useThemeStyles

  • Parameters:

    ArgumentTypeRequiredDefault ValueDescription
    lightColorstring(none)The color to be used in the light color scheme.
    darkColorstring(none)The color to be used in the dark color scheme.
  • Returns: A color string that corresponds to the active color scheme, but only when called within SmartStyles.create() or SmartStyles.helper().

Example:

import {SmartStyles, themeColor, tc} from 'react-native-smart-styles';

const styles = SmartStyles.create({
container: {
backgroundColor: tc('#fff', '#333'), // Light mode: white, Dark mode: dark grey
},
text: {
color: themeColor('#000', '#fff'), // Light mode: black, Dark mode: white
},
});

// The styles object now contains theme-aware properties that adapt based on the active color scheme.

By integrating these functions directly into your style creation process and forwarding them into useThemeStyles (forward only when using SmartStyles.helper()), you ensure that your application's visual elements adapt seamlessly to the current theme, providing a consistent and user-friendly experience.

Hooks

useThemeStyles()

This hook takes a stylesheet (ideally created using SmartStyles.helper()) and returns a formatted stylesheet that adapts to the active color scheme (either 'dark' or 'light').

IMPORTANT

Do not pass styles that were generated using SmartStyles.create(), if you will, it will convert sizes more than once and will result false size

  • Parameters:

    ArgumentTypeRequiredDefault ValueDescription
    stylesheetNamedStyles<any>(none)A style object created by SmartStyles.helper().
  • Returns: A style object formatted according to the active color scheme.

Example:

import { useThemeStyles, tc } from 'react-native-smart-styles';

const Component = (props) => {
const styles = useThemeStyles(themedStyles);
return (
<View style={styles.container}/>
);
};

const themedStyles = SmartStyles.helper({
container: {
padding: 20,
},
text: {
fontSize: 18,
color: tc('#fff', '#000'),
},
});

This function allows developers to seamlessly integrate theme-based styling in their React Native applications, ensuring consistency across different user preferences for dark or light modes.


useTheme()

The useTheme hook provides an easy way to access the currently active theme within your React Native application. This hook does not require any parameters and returns a SmartStylesTheme, which is a string that can be either 'dark' or 'light'.

Example:

import { useTheme } from 'react-native-smart-styles';

const MyComponent = () => {
const theme = useTheme(); // Returns 'dark' or 'light'

return (
<Text style={{ color: theme === 'dark' ? '#FFF' : '#000' }}>
Current theme is {theme}.
</Text>
);
};

export default MyComponent;
info

Using useTheme allows your components to dynamically adjust their styling based on the current theme setting. This is particularly useful for creating responsive designs that adapt to user preferences or system settings, enhancing the overall user experience.

This hook helps maintain consistency and simplicity in accessing the theme state throughout your application without manually passing around theme data.


Methods

Please note

DON'T use notifyThemeListeners because it will be removed in the future

tip

Don't use these listeners unless there is no other choice, use useTheme instead

addThemeListener

The addThemeListener method allows you to add a listener function that will be called whenever the theme changes. The listener function receives the current theme as an argument.

  • Parameters:
ArgumentTypeRequiredDefault ValueDescription
listenerFunction(none)A function that takes one argument (theme). This function will be called whenever the theme changes, providing the current theme.
  • Returns: The ID of the listener. This ID can be used to remove the listener later.

Example

import { SmartStyles } from 'react-native-smart-styles';

// Define the theme listener function
const themeListener = (theme) => {
console.log('Current theme:', theme);
};

// Add the theme listener
const listenerId = SmartStyles.addThemeListener(themeListener);

console.log('Listener ID:', listenerId);

removeThemeListener

The removeThemeListener method allows you to remove a previously added theme listener using its ID.

  • Parameters:
ArgumentTypeRequiredDefault ValueDescription
listenerIdstring(none)The ID of the listener to be removed. This is the ID returned by addThemeListener.

Example

import { SmartStyles } from 'react-native-smart-styles';

// Assume you have added a listener and obtained the listener ID
const listenerId = 'example-listener-id';

// Remove the theme listener
SmartStyles.removeThemeListener(listenerId);

Complete Example

Below is a complete example demonstrating the usage of both addThemeListener and removeThemeListener methods.

import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import { SmartStyles } from 'react-native-smart-styles';

const App = () => {
const [activeTheme, setActiveTheme] = useState();

useEffect(() => {
// Define the theme listener function
const themeListener = (theme) => {
setActiveTheme(theme);
};

// Add the theme listener and get the listener ID
const listenerId = SmartStyles.addThemeListener(themeListener);

// Clean up the listener when the component unmounts
return () => {
SmartStyles.removeThemeListener(listenerId);
};
}, []);

return (
<View>
<Text>Current theme: {activeTheme}</Text>
</View>
);
};

export default App;

By using these methods, you can effectively manage theme changes in your application and ensure that your components respond to updates accordingly.