Reputation: 2090
I know there is Animated API for React Native but as far as I've seen it's very complicated than what I want to implement in this particular situation.
Now I have a button that has a changing text state inside while scrolling to the page. The texts' length differ so button has to stretch or shrink. But of course this happens instantly, I want it to stretch or shrink smoothly. In web, we could easily do something like this in CSS ;
transition: all 0.3s ease;
When you don't want to add extra animations this can be enough. So what is the equvialent of this behaviour in React Native?
Upvotes: 1
Views: 7631
Reputation: 2352
The equivalent to CSS transitions is LayoutAnimation from React Native. Before you make a state change regarding the button, you configure the LayoutAnimation. Then the next state update will be animated at that position. This can look like this:
export default function App() {
const [text, setText] = React.useState("This is an example");
React.useEffect(() => {
setTimeout(() => {
LayoutAnimation.spring();
setText("This is an another example");
}, 1500);
}, [])
return (
<View style={styles.container}>
<View style={{backgroundColor: 'red', padding: 20}}>
<Text>{text}</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
}
});
Prerequisite is always that it goes via a state change. Just play around with a sample View Box and give the width and height over the useState hook. If you configure your LayoutAnimation before you write setWidth, then the component with the state will be animated automatically.
Upvotes: 6