Skip to content

Instantly share code, notes, and snippets.

@dhrrgn
Last active October 23, 2015 20:10
Show Gist options
  • Save dhrrgn/57f5d54daa152b658b41 to your computer and use it in GitHub Desktop.
Save dhrrgn/57f5d54daa152b658b41 to your computer and use it in GitHub Desktop.
/**
* @providesModule ProgressBar
*/
import React, { Animated, PropTypes, StyleSheet, View, } from 'react-native';
class ProgressBar extends React.Component {
static propTypes = {
progress: PropTypes.number,
progressColor: PropTypes.string,
trackColor: PropTypes.string,
style: View.propTypes.style,
};
static defaultProps = {
progressColor: 'rgb(0, 255, 0)',
trackColor: 'rgb(220, 220, 0)',
progress: 0.0,
style: {},
};
constructor(props) {
super(props);
this.state = {
value: new Animated.Value(0),
};
}
shouldComponentUpdate(newProps, newState) {
if (newProps.progress !== this.props.progress) {
this._animateToValue(newProps.progress);
}
return true;
}
render() {
let trackStyles = {
backgroundColor: this.props.trackColor,
};
let progressStyles = {
backgroundColor: this.props.progressColor,
width: this.state.value,
};
return (
<View style={[styles.track, trackStyles, this.props.style]} onLayout={this._onLayout.bind(this)}>
<Animated.View style={[styles.progress, progressStyles]} />
</View>
);
}
_animateToValue(newValue) {
Animated.timing(this.state.value, {
duration: 200,
toValue: newValue * this.state.width,
}).start();
}
_onLayout({nativeEvent}) {
this.setState({
width: nativeEvent.layout.width
}, () => {
this._animateToValue(this.props.progress);
});
}
}
// -----------------------------------------------------------------------------
var styles = StyleSheet.create({
track: {
flex: 1,
},
progress: {
position: 'absolute',
top: 0,
left: 0,
bottom: 0,
}
});
export default ProgressBar;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment