How to use CountDown Timer in React Native?

Published On: 16/07/2022 | Category: React Native

Hi Guys,

This article will provide example of how to use countdown timer in react native. if you have question about countdown timer in react-native then I will give simple example with solution. Here you will learn how to create countdown timer using react native. you'll learn how to implement countdown timer in react native. You just need to some step to done react native countdown timer example.

Let's start following example:

Step 1: Download Project

In the first step run the following command to create a project.

expo init ExampleApp
Step 2: Install and Setup

First of all you have to install react-native-countdown-component package and moment package.

npm install react-native-countdown-component
npm install moment --save
Step 3: App.js

In this step, You will open the App.js file and put the code.

import React, { useState, useEffect } from 'react';
import { SafeAreaView, StyleSheet, Text, View } from 'react-native';
import CountDown from 'react-native-countdown-component';
import moment from 'moment';

const App = () => {
    const [totalDuration, setTotalDuration] = useState(0);

    useEffect(() => {
        let date = moment().utcOffset('+05:30').format('YYYY-MM-DD hh:mm:ss');
        let expirydate = '2022-07-16 12:00:00';

        let diffr = moment.duration(moment(expirydate).diff(moment(date)));

        var hours = parseInt(diffr.asHours());
        var minutes = parseInt(diffr.minutes());
        var seconds = parseInt(diffr.seconds());

        var d = hours * 60 * 60 + minutes * 60 + seconds;
        
        setTotalDuration(d);
    }, []);

    return (
        <SafeAreaView style={styles.container}>
            <View style={styles.container}>
                <Text style={styles.title}>
                    React Native CountDown Timer 
                </Text>
                <CountDown
                    until={totalDuration}
                    timetoShow={('H', 'M', 'S')}
                    onFinish={() => alert('finished')}
                    onPress={() => alert('hello')}
                    size={20}
                />
            </View>
        </SafeAreaView>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        padding: 10,
        justifyContent: 'center',
        alignItems: 'center',
    },
    title: {
        textAlign: 'center',
        fontSize: 20,
        fontWeight: 'bold',
        padding: 20,
    },
});

export default App;
Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output :

It will help you...