Last active
November 23, 2017 22:08
-
-
Save clempat/b2266320d2182de1102a7113f08f8b37 to your computer and use it in GitHub Desktop.
React Expander Component with GSAP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Expander allow to add expand function to components | |
* Warning: this use not adviced api from React (Context) | |
* So Check when react updates | |
*/ | |
import React from 'react'; | |
import styled from 'styled-components'; | |
import PropTypes from 'prop-types'; | |
import { TweenLite } from 'gsap'; | |
export const withExpander = (options = {}) => WrappedComponent => class extends React.Component { | |
static childContextTypes = { | |
__expander_open: PropTypes.bool, | |
} | |
state = { | |
open: options.open || false | |
} | |
getChildContext() { | |
return { | |
__expander_open: this.state.open, | |
} | |
} | |
toggle = () => { | |
this.setState(prevState => ({ | |
open: !prevState.open, | |
})) | |
} | |
render() { | |
return <WrappedComponent expander={{toggle: this.toggle}} {...this.props} /> | |
} | |
} | |
const Wrapper = styled.div` | |
overflow: hidden; | |
` | |
export class Expandable extends React.Component { | |
static propTypes = { | |
children: PropTypes.any, | |
} | |
static contextTypes = { | |
__expander_open: PropTypes.bool, | |
} | |
componentDidMount() { | |
this.toggleSlideDown(this.context.__expander_open); | |
} | |
componentWillUpdate(nextProps, nextState, nextContext) { | |
if (nextContext.__expander_open !== this.context.__expander_open) { | |
this.toggleSlideDown(nextContext.__expander_open); | |
} | |
} | |
toggleSlideDown = (open) => { | |
if (open) { | |
TweenLite.set(this._expandable, {height: 'auto'}); | |
TweenLite.from(this._expandable, .3, { height: 0 }); | |
} else { | |
TweenLite.to(this._expandable, .3, { height: 0 }); | |
} | |
} | |
render() { | |
return <Wrapper innerRef={dom => this._expandable = dom}> | |
{this.props.children} | |
</Wrapper> | |
} | |
} | |
export const expanderShape = PropTypes.shape({ | |
toggle: PropTypes.func, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment