Steven Matthews
Steven Matthews

Reputation: 11325

How to use React Spring in a HOC?

I am sure that this is relate to me not totally understanding how React Spring works or maybe HOCs.

I am trying to create a HOC for React that adds a React Spring animation (slides the child component in from the left)

const SlideLeft = WrappedComponent => {
  const [props] = useSpring({
    translateX: "0",
    from: { translateX: "1000vw" }
  });
  return (
    <animated.div style={props}>
      <WrappedComponent />
    </animated.div>
  );
};

And then later on, in another component, I have this:

    <SlideLeft>
      <Categories />
    </SlideLeft>

I would think this would work, but instead I am getting the error:

TypeError: arr[Symbol.iterator] is not a function

I found this page which suggested changing it to just const props:

https://github.com/react-spring/react-spring/issues/616

However, when I do that I get the error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `SlideLeft`.

So I'm not quite sure how to get a HOC working with React Spring.

Any information would be illuminating.

Upvotes: 0

Views: 606

Answers (1)

user9408899
user9408899

Reputation: 4540

Define wrapper like this:

 export function SlideLeft(props) {
      const animationProps = useSpring({
        from: { transform: "translate3d(-100%,0,0)" },
        to: { transform: "translate3d(0%,0,0)" }
      });

      return <animated.div style={{ ...animationProps }}> {props.children} </animated.div>;
    }

And call from the parent component like this:

  <SlideLeft>
    <yourComponent/>
  </SlideLeft>

Note that in the from and to objects, I am using the same unit, namely percentage. Using the same unit is important. If you use different unit, or pass unit-less numbers it won't work.

Upvotes: 1

Related Questions