I'm trying to use a datepiker in react native to consolelog the piked date when I click on the Button i want to console.log(slected) selected date
const [text, setTextname] = useState();
const [mydate, setDate] = useState(new Date());
const [displaymode, setMode] = useState('date');
const [isDisplayDate, setShow] = useState(false);
const changeSelectedDate = (event, selectedDate) => {
const currentDate = selectedDate || mydate;
let date = moment(selectedDate).format('DD/MM/YYYY');
console.log('dadad', date);
setTextname(date);
setShow(false);
};
const showMode = currentMode => {
setShow(true);
setMode(currentMode);
};
const displayDatepicker = () => {
showMode('date');
};
function getdata() {
console.log('sdsds', text);
}
<Button onPress={displayDatepicker} title="Show date picker!" />
{isDisplayDate && (
<DateTimePicker
testID="dateTimePicker"
value={mydate}
mode={displaymode}
is24Hour={true}
display="default"
onChange={text => changeSelectedDate()}
// onChange={changeSelectedDate}
/>
)}
<View style={styles.buttonw}>
<Button
color="#7743DB"
title="Lets Go"
type="submit"
onPress={() => getdata()}
/>
</View>
i have displayed the datepiker but i am not able to pick a date and pass it to getdata
CodePudding user response:
You have to set date on setDate state in your change date function.
setDate(date);----->add this
setTextname(date);
CodePudding user response:
Remove
const [text, setTextname] = useState();
Replace in function changeSelectedDate
setTextname(date);
with
setDate(date);
and
const currentDate = selectedDate || mydate
by
const currentDate = selectedDate
and lastly
function getdata() {
console.log('sdsds',mydate);
}
changes to function
const changeSelectedDate = (event, selectedDate) => {
setDate(selectedDate);
setShow(false);
};
function getdata() {
let date = moment(mydate).format('DD/MM/YYYY');
console.log('sdsds',date);
}
CodePudding user response:
you can save the date to State using onDateChange Method
onDateChange={(text) => {console.log(text)}