Hi everyone !
First article, ever, I suck at Markdown, let's get to the point.
I've been following an online course (https://openclassrooms.com/fr/courses/4902061-developpez-une-application-mobile-react-native/), which uses Class Components.
2020, we're woke (kinda), I'm doing it with Function Components.
Now some parts have been written taking Classes and React Navigation V4 as a base (which will also require another article in the future), so here's a code to make animations work with Function Components.
Here's the code with a Class :
// Animations/EnlargeShrink.js
import React from 'react'
import { Animated } from 'react-native'
class EnlargeShrink extends React.Component {
constructor(props) {
super(props)
this.state = {
viewSize: new Animated.Value(this._getSize())
}
}
_getSize() {
if (this.props.shouldEnlarge) {
return 80
}
return 40
}
// La méthode componentDidUpdate est exécuté chaque fois que le component est mise à jour, c'est l'endroit parfait pour lancer / relancer notre animation.
componentDidUpdate() {
Animated.spring(
this.state.viewSize,
{
toValue: this._getSize()
}
).start()
}
render() {
return (
<Animated.View
style={{ width: this.state.viewSize, height: this.state.viewSize }}>
{this.props.children}
</Animated.View>
)
}
}
export default EnlargeShrink
And here's the code with a function :
import React, { useEffect, useState } from 'react'
import { Animated } from 'react-native'
export default function FavTouch({children, shouldEnlarge}) {
const [size, setSize] = useState(new Animated.Value(shouldEnlarge ? 80:40))
useEffect(() => {
Animated.spring(
size,
{
toValue: shouldEnlarge ? 80 : 40,
useNativeDriver: false
},
).start()
}, [shouldEnlarge])
return (
<Animated.View style={{width: size, height: size}}>
{children}
</Animated.View>
)
}
Feel free to give heads-up/changes if needed, see you around !
Top comments (0)