In this blog post, We’ll learn, how to develop a simple react native app, where user can click a button to open date picker, select a date and come back to previous screen, with the selected date displayed to a label
In this Example, we will be using
hooks
- inside DatePicker
componentDatePicker
to App
I am going to use react-native-modal-datetime-picker
npmjs module in this example. I am using version 8.7.1
and the github link for the repo is here
Assuming that you have already created react native project, install the following package in terminal using the following command
Create a new file named DatePicker.jsx
and paste the following code
import React, { useState } from "react";
import { View, Button } from "react-native";
import DateTimePickerModal from "react-native-modal-datetime-picker";
const DatePicker = ({ selectedDateCallback }) => {
const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
const showDatePicker = () => {
setDatePickerVisibility(true);
};
const hideDatePicker = () => {
setDatePickerVisibility(false);
};
const handleConfirm = (date) => {
console.log("A date has been picked: ", date);
hideDatePicker();
//send back to parent component
selectedDateCallback(date);
};
return (
<View>
<Button onPress={showDatePicker} title="Show Date Picker "></Button>
<DateTimePickerModal
isVisible={isDatePickerVisible}
mode="date"
onConfirm={handleConfirm}
onCancel={hideDatePicker}
/>
</View>
);
};
export default DatePicker;
Now, Lets come back to App.js
First, Add Import
Next, Add the following code above return()
method
Atlast, Add the following code in return()
method
Now, Save all the changes run the app in iOS Simulator or Android emulator or your own device to see the output. You can find the source code for the project here
Find the screenshots below: