Skip to content

Instantly share code, notes, and snippets.

@bsansouci
Created July 15, 2015 20:09
Show Gist options
  • Save bsansouci/3a8cc7f1dddaebbfabda to your computer and use it in GitHub Desktop.
Save bsansouci/3a8cc7f1dddaebbfabda to your computer and use it in GitHub Desktop.
/*eslint-disable */
import React, {PropTypes} from 'react';
import {TransitionSpring} from '../src/Spring';
const Demo = React.createClass({
getInitialState() {
return { open: false };
},
onOpenModal() {
this.refs.modal1.open();
},
render() {
return (
<div>
<button onMouseDown={this.onOpenModal}>Open Modal</button>
<Modal ref="modal1" />
</div>
);
},
});
const Modal = React.createClass({
propTypes: {
onClose: PropTypes.func.isRequired,
},
getInitialState() {
return { open: false };
},
endValue() {
if(!this.state.open) return {};
return {
key: {
opacity: {
val: 1
}
}
};
},
willEnter() {
return {
opacity: {
val: 0
}
};
},
willLeave(key, endValue, currentValue) {
if (this.state.open === false && currentValue[key].opacity.val === 0) {
return null;
}
return {
opacity: {
val: 0
}
}
},
render() {
return (
<TransitionSpring endValue={this.endValue} willLeave={this.willLeave} willEnter={this.willEnter}>
{config =>
config.key ?
<div className="modal" style={{ opacity: config.key.opacity.val }}>
Modal <button onClick={this.onClose}>&times;</button>
</div>
: <span />
}
</TransitionSpring>
);
},
onClose() {
this.setState({ open: false });
},
open() {
this.setState({ open: true });
},
});
export default Demo;
@bsansouci
Copy link
Author

The code could look a lot nicer if we had inline data structures for willEnter and willLeave.

const Modal = React.createClass({

  propTypes: {
    onClose: PropTypes.func.isRequired,
  },

  getInitialState() {
    return { open: false };
  },

  render() {
    return (
      <TransitionSpring 
        endValue={this.state.open ? {key: {opacity: {val: 1}}} : {}} 
        willLeave={{opacity: {val: 0}}} 
        willEnter={{opacity: {val: 0}}}>
        {config =>
          config.key ?
            <div className="modal" style={{ opacity: config.key.opacity.val }}>
              Modal <button onClick={() => this.setState({open: false})}>&times;</button>
            </div>
          : <span />
        }
      </TransitionSpring>
    );
  },

  open() {
    this.setState({ open: true });
  },
});

That said it's just sugar, and it requires use to cover more small edge cases (and meaning we need a default willLeave that checks if the current reached the destination). So I'm not sure if it's worth it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment