My skills in react native is basic, i want to create a basic countdown, when i click play the countdown start, like this example:
My Code:
render() {
return (
<Grid>
<Row>
<Col style={styles.col_exercise}>
<Image source={require('../../assets/images/done.png')} resizeMode="contain" style={styles.icon_videoexercise} />
<Text style={styles.titlecol_exercise}>Done</Text>
</Col>
<Col style={styles.col_exercise}>
<View style={{borderWidth: 2, borderColor: '#f39c12', borderRadius: 50, height: 100, width: 100,alignItems: 'center',
justifyContent: 'center'}}>
<Text style={{fontSize: 18, color: '#000'}}>
00:30
</Text>
</View>
</Col>
<Col style={styles.col_exercise}>
<Image source={require('../../assets/images/play.png')} resizeMode="contain" style={styles.icon_videoexercise} />
<Text style={styles.titlecol_exercise}>Play</Text>
</Col>
</Row>
</Grid>
);
}
constructor(props) {
super(props);
this.state = { timer: 30 };
}
componentDidMount() {
this.clockCall = setInterval(() => {
this.decrementClock();
}, 1000);
}
componentWillUnmount() {
clearInterval(this.clockCall);
}
decrementClock = () => {
this.setState((prevstate) => ({ timer: prevstate.timer-1 }));
};
You can create a countdown with setInterval
. Every second this.decrementClock()
will be called after the component mounts.
You will want to render this.state.timer
in your render method.
constructor(props) {
super(props);
this.state = { timer: 30 };
}
startTimer = () => {
this.clockCall = setInterval(() => {
this.decrementClock();
}, 1000);
}
decrementClock = () => {
if(this.state.timer === 0) clearInterval(this.clockCall)
this.setState((prevstate) => ({ timer: prevstate.timer-1 }));
};
componentWillUnmount() {
clearInterval(this.clockCall);
}
In render add the button with Onpress
event listener.
<button Onpress={this.startTimer}> Play </button>
<Text style={{fontSize: 18, color: '#000'}}>
{this.state.timer === 0 ? 'Times Up!' : {this.state.timer} }
</Text>
To prevent negative numbers try this:
decrementClock = () => {
this.setState((prevstate) => ({
timer: prevstate.timer-1
}), () => {
if(this.state.timer === 0) {
clearInterval(this.clockCall)
}
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With