Control pressable component styles #204
Unanswered
SergeyYuhimovich
asked this question in
Q&A
Replies: 1 comment
-
My working example and appropriate piece of theme below: import {
backgroundColor,
BackgroundColorProps,
border,
BorderProps,
composeRestyleFunctions,
createVariant,
ResponsiveValue,
spacing,
SpacingProps,
useRestyle,
VariantProps,
} from "@shopify/restyle";
import { ReactNode, useState } from "react";
import {
Pressable as DefaultPressable,
PressableProps as DefaultPressableProps,
View as DefaultView,
ViewProps as DefaultViewProps,
} from "react-native";
import { Theme } from "../../theme";
type RestyleProps = SpacingProps<Theme> &
BorderProps<Theme> &
BackgroundColorProps<Theme> &
VariantProps<Theme, "pressable">;
const restyleFunctions = composeRestyleFunctions<Theme, RestyleProps>([
spacing,
border,
backgroundColor,
createVariant({ themeKey: "pressable" }),
]);
type ViewProps = RestyleProps & DefaultViewProps;
export const View = ({ children, ...rest }: ViewProps) => {
const props = useRestyle(restyleFunctions, rest);
return <DefaultView {...props}>{children}</DefaultView>;
};
type PressableVariants = Exclude<keyof Theme["pressable"], "defaults">;
type ResponsivePressableVariants = ResponsiveValue<PressableVariants, Theme["breakpoints"]>;
export const Pressable = ({ children, onPressIn, onPressOut, ...rest }: DefaultPressableProps) => {
const [variant, setVariant] = useState<ResponsivePressableVariants>("regular");
return (
<DefaultPressable
{...rest}
onPressIn={(e) => {
setVariant("pressed");
onPressIn && onPressIn(e);
}}
onPressOut={(e) => {
setVariant("regular");
onPressOut && onPressOut(e);
}}
>
<View variant={variant}>{children as ReactNode}</View>
</DefaultPressable>
);
};
. . . . . .
pressable: {
defaults: {
backgroundColor: "primary",
padding: {
phone: "s",
tablet: "m",
},
margin: {
phone: "xs",
tablet: "m",
},
borderRadius: {
phone: "xs",
},
},
regular: {
backgroundColor: "primary",
opacity: 1,
},
pressed: {
backgroundColor: "secondary",
opacity: 0.8,
},
},
. . . . . . |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
What is the best way to style dynamic components, which style could change (i.e. during user interaction)?
For instance, I've created this custom Button component:
and using it like this somewhere outside:
So the task is to somehow apply different styles when button is being pressed. Do I need to create another variant but for pressed state (like,
primaryPressed
) and somehow change the variant from outside? Or is there something I missed when reading docs and there's easier way to do this?Beta Was this translation helpful? Give feedback.
All reactions