If you try to pass functional (non react class) component to Animated.createAnimatedComponent
it throws an error that says
Stateless functional components are invalid as children of createAnimatedComponent
Coming from an app that uses react hooks, basically all of my component are functional.
Is there a way / helper that can allow to pass these to createAnimatedComponent
without wrapping them in Animated.View
or even just View
?
Here is an example of component that I want to make animatable
function MyComponent({ someProp }) {
const [counter, setCounter] = useState(0);
return (
<View>
<Text>{counter}</Text>
</View>
);
}
It has several advantages, first of all, functional components are just simple javascript functions that accept the information in the form of prop and return the react element, which is HTML content. There is no need to use the render() method inside functional components.
In functional components, there is no need for a render function. A functional component is just a plain JavaScript function that returns JSX. A class component is a JavaScript class that extends React.
Using componentDidMount in functional components with useEffect. This is how we can perform the equivalent of componentDidMount in functional components using the useEffect Hook: useEffect(() => { // Inside this callback function we perform our side effects. });
How about this HOC
export function withAnimated(
WrappedComponent: React.ComponentType<any>,
): ComponentType {
const displayName =
WrappedComponent.displayName || WrappedComponent.name || 'Component';
class WithAnimated extends React.Component {
static displayName = `WithAnimated(${displayName})`;
render(): React.ReactNode {
return <WrappedComponent {...this.props} />;
}
}
return Animated.createAnimatedComponent(WithAnimated);
}
export const AnimatedGradientButton = withAnimated(GradientButton);
As far as I can tell, your options are:
1) Change to class component
2) Wrap your component in a View
which you then animate
3) Use react-native-animatable
(or a solution similar as this offers): check
here for a combination of the library and refs
4) Maybe a solution similar to this one would suit you better. Combination of useRef
and useEffect
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With