Is it possible to infer variants from createStyleSheet as component props types #150
-
based on the docs, we need to define props manually, but i think it seems redundant since i believe we can use information from something like this import { Ref, forwardRef } from 'react'
import { Pressable, View } from 'react-native'
import { createStyleSheet } from 'react-native-unistyles'
export type ButtonProps = {
size: ExtractStyleSheetVariant<typeof stylesheet>['size'] // shoule be 'xs' | 'sm'
}
export const Button = forwardRef(
({ ...props }: ButtonProps, ref: Ref<View>) => {
return <Pressable accessibilityRole="button" ref={ref} {...props} />
},
)
const stylesheet = createStyleSheet(_theme => ({
container: {
variants: {
size: {
xs: {
padding: 10,
},
sm: {
padding: 12,
},
},
},
},
})) not sure if this is already possible or not, since i couldn't find a way to do this in the docs |
Beta Was this translation helpful? Give feedback.
Answered by
jpudysz
Feb 19, 2024
Replies: 1 comment 2 replies
-
for now i'm doing this manually like this import { Ref, forwardRef } from 'react'
import {
Pressable,
PressableProps,
StyleProp,
View,
ViewStyle,
} from 'react-native'
import { createStyleSheet, useStyles } from 'react-native-unistyles'
// this
type Size = keyof ReturnType<typeof stylesheet>['container']['variants']['size']
export type ButtonProps = PressableProps & {
size: Size
style?: StyleProp<ViewStyle>
}
export const Button = forwardRef(
({ size, style, ...props }: ButtonProps, ref: Ref<View>) => {
const { styles } = useStyles(stylesheet, { size })
return (
<Pressable
accessibilityRole="button"
ref={ref}
style={() => [styles.container, style]}
{...props}
/>
)
},
)
const stylesheet = createStyleSheet(_theme => ({
container: {
variants: {
size: {
xs: {
padding: 10,
},
sm: {
padding: 12,
},
},
},
},
})) |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey! I didn't expose the type, but Unistyles indeed infers the type for the
useStyles
hook. It's calledExtractVariantNames
, and you can find it here:react-native-unistyles/src/types/variants.ts
Line 1 in 31677ce
You need to pass
typeof stylesheet
to it. Nonetheless, I think it's easier to simply type your props because you also need to select the variant name from the result.In this case, I believe simplicity is more important than complexity.