Skip to content

Instantly share code, notes, and snippets.

@aitoroses
Last active January 23, 2018 04:44
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aitoroses/e9b3d77b637fc6ad9087 to your computer and use it in GitHub Desktop.
Save aitoroses/e9b3d77b637fc6ad9087 to your computer and use it in GitHub Desktop.
Dynamics.js and React
export function AnimateMixinFactory(stateName) {
var animateMixin = {
getInitialState() {
return {
[stateName]: {}
}
}
};
animateMixin[stateName] = function(props) {
this.setState({
[stateName]: props
});
}
return animateMixin;
}
var dynamics = require('dynamics.js/lib/dynamics');
export class AnimationComponent extends React.Component {
static propTypes = {
properties: React.PropTypes.object.isRequired,
options: React.PropTypes.object
}
_animate() {
var el = React.findDOMNode(this);
// Run amination
dynamics.animate(el, this.props.properties, this.props.options || {type: dynamics.spring})
}
componentDidMount() {
this._animate();
}
componentDidUpdate() {
this._animate();
}
render() {
return (
<div className="animation-container">
{this.props.children}
</div>
)
}
}

Usage with a component

import {AnimateMixinFactory} from './AnimateMixinFactory';
import {AnimationComponent as Animation} from './AnimationComponent'

import {decorate as mixin} from 'react-mixin';

// Create a mixin for the class ( will provide {state: animateTest: {}} and this.animateTest() )

@mixin(AnimateMixinFactory('animateTest'))
class DynamicsExample extends React.Component{
  handleClick() {
    // Calculate the next position
    var newPosition = this.state.animateTest.translateX || 0;
    // Set animation state
    this.animateTest({
      translateX: newPosition
    })
  }
  render() {
  
    /* Animation controls the transform CSS property of it's child using dynamics.js */

  	return(
      <Animation properties={this.state.animateTest}>
        <div onClick={this.handleClick.bind(this)}>
          A div that can be animated
        </div>
      </Animation>
  	)
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment