React native. How do I, on press, make the card seemed pressed (like on press, shrink…
- User
React native. How do I, on press, make the card seemed pressed (like on press, shrink the box a bit)? Is there already a component for this?
- Assistant
React native. How do I, on press, make the card seemed pressed (like on press, shrink the box a bit)? Is there already a component for this?
In React Native, you can achieve a "pressed" effect by scaling the card down slightly when the user presses it. You can use the Animated API to animate the scaling effect. Below is how you can create this effect:
Animated.View to wrap your Card.onPressIn and onPressOut handlers to adjust the scale when the card is pressed.Here's an example of how you can implement this:
import React, { useState } from 'react';
import { Animated, View, Pressable, Text, StyleSheet } from 'react-native';
const AnimatedCard = () => {
const [scale] = useState(new Animated.Value(1));
const handlePressIn = () => {
Animated.spring(scale, {
toValue: 0.95,
useNativeDriver: true,
}).start();
};
const handlePressOut = () => {
Animated.spring(scale, {
toValue: 1,
useNativeDriver: true,
}).start();
};
return (
<View style={styles.container}>
<Pressable
onPressIn={handlePressIn}
onPressOut={handlePressOut}
onPress={() => console.log('hi')}
>
<Animated.View style={[styles.card, { transform: [{ scale }] }]}>
<View style={styles.cardHeader}>
<Text style={styles.title}>Free Buckeye Donuts</Text>
<Text style={styles.subheader}>20 minutes ago</Text>
</View>
</Animated.View>
</Pressable>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
card: {
backgroundColor: '#fff',
padding: 20,
borderRadius: 10,
elevation: 2,
},
cardHeader: {
flexDirection: 'column',
justifyContent: 'space-between',
},
title: {
fontSize: 18,
fontWeight: 'bold',
},
subheader: {
fontSize: 14,
color: '#777',
},
});
export default AnimatedCard;
Animated Value: const [scale] = useState(new Animated.Value(1)); creates an Animated.Value that represents the scale of the card. The initial value is set to 1 (no scaling).
Press Handlers:
handlePressIn animates the scale to 0.95 when the user presses the card.handlePressOut animates the scale back to 1 when the press is released.Animated.View: Wrap the card content inside an Animated.View and bind the scale transformation to the animated value.
Styles: Basic styling to create a card-like appearance.
You can refine the styling and content of the card as needed. This approach gives a nice feedback effect to the user, making it clear that the card is being pressed.