Skip to content

Instantly share code, notes, and snippets.

@reu
Last active April 25, 2017 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save reu/fa397ffeb2fb23cb6a5216157a6661d6 to your computer and use it in GitHub Desktop.
Save reu/fa397ffeb2fb23cb6a5216157a6661d6 to your computer and use it in GitHub Desktop.
import React, {
Component,
PropTypes,
} from "react";
import {
Animated,
View,
} from "react-native";
class Collapsable extends Component {
static propTypes = {
collapsed: PropTypes.bool,
};
state = {
animation: new Animated.Value(0),
firstRender: true,
};
close() {
Animated.timing(this.state.animation, {
toValue: 0,
duration: 200,
}).start(() => this.setState({ collapsed: true }));
}
open() {
Animated.timing(this.state.animation, {
toValue: this.state.height,
duration: 200,
}).start(() => this.setState({ collapsed: false }));
}
componentDidMount() {
this.props.collapsed ? this.close() : this.open();
}
componentWillReceiveProps(nextProps) {
const shouldCollapse = nextProps.collapsed;
if (this.state.collapsed != shouldCollapse) {
shouldCollapse ? this.close() : this.open();
}
}
render() {
const height = this.state.firstRender ? null : this.state.animation;
return (
<Animated.View style={{ height, overflow: "hidden" }}>
<View onLayout={event => {
if (this.state.firstRender) this.setState({ height: event.nativeEvent.layout.height, firstRender: false });
}}>
{ this.props.children }
</View>
</Animated.View>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment