04-Apr-2023
.
Admin
Hi Guys,
This is a short guide on how to create community dateTimePicker in react native. I’m going to show you about how to implement community dateTimePicker in react native. if you have question about how to use community dateTimePicker in react native then I will give simple example with solution. I would like to show you how to add community dateTimePicker in react native. So, let's follow few step to create example of react native community dateTimePicker 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 DateTimePicker package.
npm install @react-native-community/datetimepicker --save
Step 3: App.js
In this step, You will open the App.js file and put the code.
import React, { useState } from 'react';
import { Button, Platform, StyleSheet, Text, View } from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
const App = () => {
const [date, setDate] = useState(new Date());
const [mode, setMode] = useState('date');
const [show, setShow] = useState(false);
const [text, setText] = useState('Empty');
const onChang = (event, selectDate) => {
const currentDate = selectDate || date;
setShow(Platform.OS === 'ios');
setDate(currentDate);
let tempDate = new Date(currentDate);
let fDate = tempDate.getDate() + '/' + (tempDate.getMonth() + 1) + '/' + tempDate.getFullYear();
let fTime = "Hours: " + tempDate.getHours() + ' | Minutes: ' + tempDate.getMinutes();
setText(fDate + '\n' + fTime);
}
const showMode = (currentMode) => {
setShow(true);
setMode(currentMode);
}
return (
<View style={styles.container}>
<Text style={styles.getDateTime}>{text}</Text>
<View style={styles.buttonContainer}>
<Button
title='Date Picker'
onPress={() => showMode('date')}
/>
</View>
<View style={styles.buttonContainer}>
<Button
title='Time Picker'
onPress={() => showMode('time')}
/>
</View>
{show &&
<DateTimePicker
testID='dateTimePicker'
value={date}
mode={mode}
is24Hour={true}
display='default'
onChange={onChang}
/>
}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFF',
},
getDateTime: {
fontWeight: 'bold',
fontSize: 20,
},
buttonContainer: {
margin: 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