React-native-paper: Use theme inside custom component style

Created on 15 Apr 2020  路  2Comments  路  Source: callstack/react-native-paper

How can I access 'theme' inside my custom styles?

I didn't find a way to access my theme to use it inside custom style.

Material-ui offers a withStyles(styles)that injects theme to be used within the style:

const styles = theme => {
    backgroundColor: theme.background
};

export default withStyles(styles)(Component);

The only workaround I came up to is this (which I don't like):

const getStyles = theme => StyleSheet.create({
    hisMessage: {
        margin: 10,
        flexDirection: 'row',
        color: theme.color
    }
});

And inside component:

const ChatMessage = ({ message, theme }) => {
    const styles = getStyles(theme);

    return (
        <View style={styles.hisMessage}>
            <Text>
                {message.text}
            </Text>
        </View>
    );
}

I don't like to do this on every component and every render. Is there another way?

question

Most helpful comment

@Bohmaster how did you end up with?

i'm also looking to have somehthing like this

const Comp = () => {
   const classes = withTheme(styles)

   return <View style={classes.wrapper} />
}

const styles = (theme) => ({wrapper: {backgroundColor: theme.colors.background}})

All 2 comments

You don't need to use StyleSheet.create. StyleSheet.create just returns the object you pass to it (after some validation etc.) anyway, so doing it every -render doesn't mean much.

Just move the whole object to render or do what you're already doing, but remove StyleSheet.create.

@Bohmaster how did you end up with?

i'm also looking to have somehthing like this

const Comp = () => {
   const classes = withTheme(styles)

   return <View style={classes.wrapper} />
}

const styles = (theme) => ({wrapper: {backgroundColor: theme.colors.background}})
Was this page helpful?
0 / 5 - 0 ratings