Skip to content

Instantly share code, notes, and snippets.

@clempat
Last active November 23, 2017 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clempat/b2266320d2182de1102a7113f08f8b37 to your computer and use it in GitHub Desktop.
Save clempat/b2266320d2182de1102a7113f08f8b37 to your computer and use it in GitHub Desktop.
React Expander Component with GSAP
/**
* 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