Skip to content

Dynamic Functions

If you need to pass a value from JSX to your stylesheet you can do so using a concept called dynamic function.

To use a dynamic function, change any stylesheet’s value from an object to a function:

const styles = StyleSheet.create(theme => ({
container: {
container: () => ({
backgroundColor: theme.colors.background,
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
})
}))

Now, you can pass any number of arguments, and all with TypeScript hints:

export const Example = ({ maxWidth, isOdd, children }) => {
return (
<View style={styles.container(maxWidth, isOdd)}>
{children}
</View>
)
}
const styles = StyleSheet.create(theme => ({
container: (maxWidth: number, isOdd: boolean) => ({
backgroundColor: theme.colors.background,
flex: 1,
justifyContent: 'center',
alignItems: 'center',
maxWidth,
borderBottomWidth: isOdd ? 1 : undefined
})
}))

Unistyles stores the arguments and may re-run your dynamic function natively with the stored copy, e.g. when your theme or runtime values change, or when a view hidden by a frozen or suspended screen is linked again. That’s why you shouldn’t pass non-serializable values:

  • functions are dropped (top-level function arguments are removed, which shifts the remaining arguments; nested ones become null)
  • Date, Map, Set and class instances lose their prototype and become plain objects (e.g. a Date becomes {})
// ❌ Don't pass functions, Dates or class instances
<View style={styles.container({ getColor: () => 'red', createdAt: new Date() })} />
// ✅ Pass already computed, serializable values
<View style={styles.container({ color: 'red', createdAt: date.getTime() })} />