In this lesson, you will learn how to create a tactile user experience by dynamically adjusting a component’s shadow elevation to simulate physical "lifting" during touch interactions.
The Concept of Tactile Depth
In the physical world, when you press down on an object, it often meets the surface it rests on. Conversely, when an object is "picked up" or hovered, it casts a larger, softer shadow, signaling to the user that the object is active or detached from the background. In React Native, we simulate this interaction by changing the elevation (on Android) or shadowOpacity/shadowRadius (on iOS) properties the moment a user initiates a press.
Implementing Dynamic Shadows
To achieve this, we use the Pressable component’s onPressIn and onPressOut events. By toggling a state variable, we can swap between a "flat" style and a "raised" style.
Consider this implementation:
const [isPressed, setIsPressed] = useState(false);
return (
<Pressable
onPressIn={() => setIsPressed(true)}
onPressOut={() => setIsPressed(false)}
style={[
styles.card,
isPressed ? styles.shadowActive : styles.shadowDefault
]}
>
<Text>Press Me</Text>
</Pressable>
);
// Style definitions
const styles = StyleSheet.create({
shadowDefault: { elevation: 2 },
shadowActive: { elevation: 10 },
});
Why it Matters for UX
When you change the shadow dynamically, you are providing visual feedback that confirms the app has registered the user's intent. If a component feels "stuck" to the screen, the user may feel a lack of responsiveness. By increasing the elevation upon interaction, you create a subtle "lift" effect that makes the UI feel tangible and reactive.
However, remember to keep these transitions subtle. Since we are updating style properties, using this in conjunction with LayoutAnimation or keeping the state logic efficient (to avoid unnecessary re-renders) ensures that the shadow jump remains smooth and performant.
Key Takeaway: Use dynamic elevation changes during touch events to visually signal component "lift," turning static elements into responsive, tactile interface pieces.