Intro
In this tutorial, you will learn how to build a basic 3dimensional looking button in react native. We will be utilizing theAnimated module that is readily available in react native.
Lets get started
CODE
importReact,{useRef}from'react';import{Text,TouchableWithoutFeedback,Animated}from'react-native';import{tailwind}from'../utils/tailwind';interfaceProps{text?:string;onPress?:()=>void;}constButton:React.FC<Props>=({text,onPress})=>{constanimation=useRef(newAnimated.Value(0)).current;consthandlePress=()=>{Animated.timing(animation,{toValue:1,duration:50,useNativeDriver:true,}).start();};consthandleButtonOut=()=>{Animated.timing(animation,{toValue:0,duration:50,useNativeDriver:true,}).start();if(onPress){onPress();}};return(<TouchableWithoutFeedbackonPressIn={handlePress}onPressOut={handleButtonOut}><Viewstyle={tailwind('rounded-full','bg-rose-700','border-rose-700')}><Animated.Viewstyle={[tailwind('rounded-full','items-center','bg-red-500','border','border-red-500',),{transform:[{translateY:animation.interpolate({inputRange:[0,1],outputRange:[-5,0],}),},],},]}><Textstyle={tailwind('font-bold','text-white','text-lg')}>{text}</Text></Animated.View></View></TouchableWithoutFeedback>);};exportdefaultButton;
Explanation
Declare a animation variable and assign the value to 0. We need wrap it in the useRef hook to make sure the animation value persists any changes that might happen outside the 3D button component.
constanimation=useRef(newAnimated.Value(0)).current;
The press animation starts on clicking the button where theinterpolate
function is invoked changing the value from0 to 1
, this causes thetranslateY
value to change from-5px to 0px
Value | translateY |
---|---|
0 | -5px |
1 | 0px |
The above table shows how the value relates to the pixels changes, you can add more values and customize it.
transform:[{translateY:animation.interpolate({inputRange:[0,1],outputRange:[-5,0],})}]
onPressIn
triggers the function to change theanimation
variable value to 1, we can assign a duration value of50
orany number
.
Animated.timing(animation,{toValue:1,duration:50,useNativeDriver:true,}).start();
onPressOut
function is triggered when the user presses out of theTouchableWithoutFeedback
where the value goes back to 0
Animated.timing(animation,{toValue:0,duration:50,useNativeDriver:true,}).start();
Hope you enjoyed this mini tutorial.
Abdul Wasey
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse