Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] How can it be used with redux @connect? #31

Open
glivera opened this issue May 5, 2018 · 1 comment
Open

[Question] How can it be used with redux @connect? #31

glivera opened this issue May 5, 2018 · 1 comment

Comments

@glivera
Copy link

glivera commented May 5, 2018

Hi
I tried to use it on a project with redux and it didn't work.
Is it possible at all?

Thank you

@cheapsteak
Copy link
Owner

cheapsteak commented May 5, 2018

Just tried it out, looks like it can, although currently takes a bit of a code (would be much simpler if we had a render-prop/FaCC connect component, which looks like it may come in v6 of react-redux)

Here's a codesandbox demo of how to get this working now - https://codesandbox.io/s/6zyv1m10rw (files of interest - index.js (where the TransitionGroup is), containers/App.js (connected component with animation), hookupAnimationLifecycles.js (helper Hoc))

connect must have the option withRef: true

You'll want to add this helper HoC function:

hookupAnimationLifecycles.js:

import { createFactory, Component } from "react";

const animationHooks = [
  "componentWillAppear",
  "componentDidAppear",
  "componentWillEnter",
  "componentDidEnter",
  "componentWillLeave",
  "componentDidLeave"
];

export default BaseComponent => {
  const factory = createFactory(BaseComponent);

  class AnimationLifecycle extends Component {
    render() {
      return factory({
        ...{ ...this.props, ...{ ref: ref => (this.ref = ref) } },
        ...this.state
      });
    }
  }

  animationHooks.forEach(hook => {
    AnimationLifecycle.prototype[hook] = function(cb) {
      if (this.ref.getWrappedInstance()[hook]) {
        this.ref.getWrappedInstance()[hook](cb);
      } else {
        cb && cb();
      }
    };
  });

  return AnimationLifecycle;
};

And to use it -

class Component extends React.Component {
  componentWillAppear () {
    // your animation stuff here
  }
  render () {
     // your render function
  }
}

compose(
  hookupAnimationLifecycles, // <-- this HoC needs to be at the first/outer-most position
  connect(mapStateToProps, mapDispatchToProps, null, {
    withRef: true // <---withRef needs to be true
  })
)(Component);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants