Search code examples
reactjsreact-nativereact-native-paper

Accessing Theme Color in React Native


I'm trying to access the primary color of the theme. I have a problem doing it since the error says "Cannot read property colors of undefined"

Pls check my code below.

import React, { memo } from "react";
import { StyleSheet, Text, withTheme } from "react-native";

const Header = ({ children }) => <Text style={styles.header}>{children}</Text>;

const styles = StyleSheet.create({
  header: {
    fontSize: 26,
    color: withTheme.colors.primary,
  },
});

export default memo(Header);

Solution

  • you can use it like this in react-native-paper

    import React, { memo } from "react";
    import { StyleSheet, Text } from "react-native";
    import { DefaultTheme } from 'react-native-paper';
    
    const theme =  ({
        ...DefaultTheme,
        colors: {
            ...DefaultTheme.colors,
        }
    });
    const Header = ({ children }) => <Text style={styles.header}>{children}</Text>;
    
    const styles = StyleSheet.create({
      header: {
        fontSize: 26,
        color: theme.colors.primary,
      },
    });
    
    export default memo(Header);
    

    If you already have a theme defined and want to import it here then you can use withTheme HOC like below

    import React, { memo } from "react";
    import { StyleSheet, Text } from "react-native";
    import { withTheme } from 'react-native-paper';
    
    const Header = ({ theme, children }) => {
        const styles = StyleSheet.create({
            header: {
                fontSize: 26,
                color: theme.colors.primary,
            },
        });
        return (
            <Text style={styles.header}>{children}</Text>
        )
    }
    
    export default memo(withTheme(Header));