Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass functional component to Animated.createAnimatedComponent

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>
  );

}
like image 667
Ilja Avatar asked Aug 05 '19 13:08

Ilja


People also ask

Can a functional component have render method?

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.

Do functional components need render?

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.

Can I use component did mount in functional component?

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. });


2 Answers

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);
}

Usage

export const AnimatedGradientButton = withAnimated(GradientButton);

like image 96
MJ Studio Avatar answered Oct 08 '22 21:10

MJ Studio


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.

like image 29
gian117 Avatar answered Oct 08 '22 22:10

gian117