React Native CountDown Timer Example

Jul 16, 2022 . Admin



Hi Guys,

I am going to explain you example of react native countdown timer example. This tutorial will give you simple example of how to use countdown timer in react native. In this article, we will implement a how to implement countdown timer in react native. This article goes in detailed on countdown timer in react-native. follow bellow step for how to create countdown timer using react native.

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...

#React Native