React Native Progressbar
React-Native
has a pretty ordinary progressbar which does not allow a lot of customizations,
but creating your own with animations is fairly simple.
First create a state
object ‘progress’ which will contain a progress value between 0 and 100 in your constructor
this.state = {
progress: 40,
}
In your render
function you can go ahead and design your Progress bar like this
render() {
return (
<View>
<View style={[styles.flexBox, styles.progressBar]}>
<View style={[styles.progressBar_left, {flex:this.state.progress}]} />
<View style={[styles.progressBar_right, {flex:100 - this.state.progress}]} />
</View>
</View>
)
}
This will basically create a progress bar where progressBar_left
style will flex the
progress colour(generally filled colour) to your progressState variable and
progressBar_right
will flex for 100 - your progress
Now go ahead and give it this styling
const styles = StyleSheet.create({
flexBox: {
flex: 1,
flexDirection: 'row',
},
progressBar: {
overflow: 'hidden',
height: 14,
borderWidth: 1,
borderColor: '#D50000',
borderRadius: 10,
},
progressBar_left: {
backgroundColor: '#D50000',
},
progressBar_right: {
backgroundColor: '#fff'
}
})
overflow: 'hidden'
in progressBar styles prevents the color from ever going out of progressbar.
To achieve spring animation you need to update your componentDidMount
and componentWillUpdate
to this
componentDidMount() {
LayoutAnimation.spring()
setTimeout(()=>{
this.setState({progress: this.props.progress})
}, 300)
}
componentWillUpdate() {
LayoutAnimation.spring()
}
You can mess around with the time out and progress variable to suite your requirements. To achieve animation on updating your state variable ‘progress’ you need to add
componentWillReceiveProps(nextProps) {
this.setState({progress: nextProps.progress})
}