Discussion on adding StyleSheet.create replacement which accepts StyleProp<T>
bfricka opened this issue · comments
Annoyingly, StyleSheet.create
only accepts named styles -> AnyStyle map. This means if you have common utilities styles, you have to spread them into each style. Here's what I mean:
// Shared example for bgColor
const bgColor = {
GREEN: { backgroundColor: '#238636' },
WHITE: { backgroundColor: '#fff' },
}
// Usage
const style = StyleSheet.create({
greenHeader: { ...bgColor.GREEN, ...padding.p4 },
whitePage: { ...bgColor.WHITE, ...padding.p4, ...padding.pb6 },
})
I don't think the runtime cost of spreading likely worth consideration. I mainly just find it annoying. Since StyleSheet.create
is just an identity, I created a similar function that defines NamedStyles
in terms of StyleProp
instead of any style:
type CreateNamedStyles<T> = { readonly [P in keyof T]: StyleProp<ViewStyle | TextStyle | ImageStyle> }
const createStyle = <T extends CreateNamedStyles<any>>(styles: T): T => styles
// Usage
const style = createStyle({
greenHeader: [bgColor.GREEN, padding.p4],
whitePage: [bgColor.WHITE, padding.p4, padding.pb6],
})
It's pretty trivial, so I'm curious what your thoughts are and if you think it's worth adding? Just like StyleSheet.create
it's basically just a type helper at this point, but it makes composition of static styles easier.
Edit: I played around a bit and createStyles
is a bit unintuitive, since React Native doesn't recursively parse styles. So I basically scrapped it in favor of my createFlatStyles
implementation. It has the same initial overhead as using spread, it's just easier to compose. If you think it's useful, I'll open a PR.
Also it would be trivial to also define a createFlatStyle
for those who want to access specific named styles without using findStyle
.
Hey, that's a good point. Shoot me a PR, this sounds like a cool feature!