Skip to content

Dynamic functions

Dynamic functions

Every style can be transformed to dynamic function to take additional parameters from JSX:

export const ExampleUnistyles = () => {
    const { styles } = useStyles(stylesheet)

    return (
        <ScrollView contentContainerStyle={styles.scrollContainer}>
            {posts.map((post, index) => (
                <View
                    key={post.key}
                    // call it as regular function
                    style={styles.post(index)}
                >
                    <Text>
                        {post.title}
                    </Text>
                </View>
            ))}
        </ScrollView>
    )
}

const stylesheet = createStyleSheet({
    scrollContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    // dynamic function
    post: (index: number) => ({
        backgroundColor: index % 2 === 0 ? 'gold' : 'silver',
    })
})

If you use a dynamic function, library will wrap it in a Proxy to make sure the correct values of breakpoints will be used:

const stylesheet = createStyleSheet(theme => ({
    scrollContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    post: (index: number) => ({
        // breakpoints and media queries works with dynamic function
        backgroundColor: {
            xs: index % 2 === 0
                ? theme.colors.gold
                : theme.colors.silver,
            sm: theme.colors.red
        }
    })
}))