React Native Date Picker Example


Share:
Published By: Admin, Published On: Jul 02, 2021, Category: React Native

Hi Guys,

In this blog, I will learn you how to use Date picker in react native. We will show example of Date picker in react native. You can easliy create react native Date picker. First, i will import DateTimePicker namespace from @react-native-community/datetimepicker, after I will make date picker in react native.

Step 1 - Create project

In the first step Run the following command for create project.

expo init MyWebtuts 
Step 2 - Installation of Dependency

In the step, Run the following command for installation of dependency.

To use DateTimePicker you need to install @react-native-community/datetimepicker package.

To install this open the terminal and jump into your project

cd paper MyWebtuts 
Run the following command
yarn add @react-native-community/datetimepicker
Step 3 - App.js

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

import React, { useState, useEffect } from 'react';
import { Button, Image, View, Platform } from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';

export default function DatepickerExample() {
    const [date, setDate] = useState(new Date(1598051730000));
    const [mode, setMode] = useState('date');
    const [show, setShow] = useState(false);

    const onChange = (event, selectedDate) => {
      const currentDate = selectedDate || date;
      setShow(Platform.OS === 'ios');
      setDate(currentDate);
      console.log(selectedDate);
    };

    const showMode = (currentMode) => {
      setShow(true);
      setMode(currentMode);
    };

    const showDatepicker = () => {
      showMode('date');
    };

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
         <View>
        <Button onPress={showDatepicker} title="Show date picker!" />
      </View>
      {show && (
        <DateTimePicker
          testID="dateTimePicker"
          value={date}
          mode={mode}
          is24Hour={true}
          display="default"
          onChange={onChange}
        />
      )}
    </View>
  );
}

Step 3 - Run project

In the last step run your project using bellow command.

expo start
Output

It will help you...

Share: