A. Gomes
A. Gomes

Reputation: 3

React Native with Typescript - Pressable pressed property

I am new in using typescript with React and I cannot use the pressed prop from Pressable in a react native app using typescript.

I am using styled components and defining a prop to change styles when Pressable is pressed:

interface Props {
    isPressed: number;
}

const MyBTN = styled.Pressable<Props>`
    background-color: blue;
    border-radius: 5px;
    display: flex;
    align-items: center;
    padding: 5px;
    background-color: ${globalStyle.primaryColor};
    box-shadow: 30px 25px 25px black;
    elevation: ${(props) => props.isPressed};
`;

const TrainerButton: React.FC<Deck> = ({title, onPress}) => {
return (
    <MyBTN onPress={onPress} isPressed={({ pressed } : any) => pressed ? 10 : 15}>
        <Text>
            { title }
        </Text>
    </MyBTN>
    )
}

I get an error on the pressed prop isPressed={({ pressed } : any) => pressed ? 10 : 15}:

No overload matches this call.
Overload 1 of 2, '(props: Omit<Omit<PressableProps & RefAttributes<View> & Props, never> & Partial<Pick<PressableProps & RefAttributes<View> & Props, never>>, "theme"> & { ...; } & { ...; }): ReactElement<...>', gave the following error.
    Type '({ pressed }: any) => 10 | 15' is not assignable to type 'number'.

  Overload 2 of 2, '(props: StyledComponentPropsWithAs<ForwardRefExoticComponent<PressableProps & RefAttributes<View>>, DefaultTheme, Props, never, ForwardRefExoticComponent<...>, ForwardRefExoticComponent<...>>): ReactElement<...>', gave the following error.
    Type '({ pressed }: any) => 10 | 15' is not assignable to type 'number'.ts(2769)

Upvotes: 0

Views: 2226

Answers (1)

Asen Mitrev
Asen Mitrev

Reputation: 693

You should be defining the Props of MyBTN in the interface Props. The type for isPressed is number but you are trying to pass in a callback.

Rather, pass a boolean to your styled component based on whether the button is pressed and then use that to show the appropriate elevation. You will also need to get the isPressed boolean from somewhere, in the case of pressable we can use the onPressIn and onPressOut callbacks:

interface Props {
    isPressed: boolean;
}

const MyBTN = styled.Pressable<Props>`
    background-color: blue;
    border-radius: 5px;
    display: flex;
    align-items: center;
    padding: 5px;
    background-color: ${globalStyle.primaryColor};
    box-shadow: 30px 25px 25px black;
    elevation: ${(props) => props.isPressed ? 10 : 15};
`;

const TrainerButton: React.FC<Deck> = ({title, onPress}) => {
   const [isPressed, setIsPressed] = useState<boolean>(false);
   const onPressIn = () => setIsPressed(true);
   const onPressOut = () => setIsPressed(false);

   return (
       <MyBTN onPress={onPress} isPressed={isPressed} onPressIn={onPressIn} onPressOut={onPressOut}>
           <Text>
               { title }
           </Text>
       </MyBTN>
   );
}

Upvotes: 1

Related Questions