i used DateTimePicker in react-native I want to show Selected Date - react-native

I am new to react native. I want to show My selected date it show in console. now in below code of dateTimePicker .what do you think the best solution please help. thanks
import React, { Component } from "react";
import DateTimePicker from "react-native-modal-datetime-picker";
export default class booking extends React.Component {
showDateTimePicker = () => {
this.setState({ isDateTimePickerVisible: true });
};
hideDateTimePicker = () => {
this.setState({ isDateTimePickerVisible: false });
};
handleDatePicked = date => {
console.warn("A date has been picked: ", date);
this.hideDateTimePicker();
};
}
render(){
return (
<View style={styles.container}>
<Text style={styles.selectDate}>Select Date:</Text>
<Button title="click:" onPress={this.showDateTimePicker} />
<Text>ateTime: {String(this.state.date)}</Text>
<DateTimePicker
maximumDate={new Date(2022, 10, 20)}
minimumDate={new Date(2021, 5, 2)}
isVisible={this.state.isDateTimePickerVisible}
mode="date"
onChange={ date => this.setState({ date }) }
onConfirm={this.showDateTimePicker}
onCancel={this.hideDateTimePicker}
/>
}

You were not using DateTimePicker properly. The simplest way to implement the DateTimePicker is to create a function that will trigger the Calendar or the Clock inside an input field when user click on the button or Text.
<TextInput
placeholder=""
onFocus={()=>RenderStartClock()}
/>
The function may be as below:
const RenderStartClock = () => {
<DateTimePicker
testID="dateTimePicker"
value={startTime}
mode={timeMode}
is24Hour={true}
display="clock"
onChange={onChangeStartTime}
/>
}

Related

using react-native-community/datetimepicker Date and time not showing

I am new to react native. I have created a screen from where I send date and time to server using datetimepicker But when I tap on show date picker then calendar is opening But issue is when I select date then this selected date not showing just show date picker button showing again. and same happens with timepicker also. please help . thanks..
here is my code
import React, {Component} from 'react';
import {View, Button, Platform} from 'react-native';
import DateTimePicker from '#react-native-community/datetimepicker';
export default class App extends Component {
state = {
date: new Date('2020-06-12T14:42:42'),
mode: 'date',
show: false,
}
setDate = (event, date) => {
date = date || this.state.date;
this.setState({
show: Platform.OS === 'ios' ? true : false,
date,
});
}
show = mode => {
this.setState({
show: true,
mode,
});
}
datepicker = () => {
this.show('date');
}
timepicker = () => {
this.show('time');
}
render() {
const { show, date, mode } = this.state;
return (
<View>
<View>
<Button onPress={this.datepicker} title="Show date picker!" />
</View>
<View>
<Button onPress={this.timepicker} title="Show time picker!" />
</View>
{ show && <DateTimePicker value={date}
mode={mode}
is24Hour={true}
display="default"
onChange={this.setDate} />
}
</View>
);
}
}
A simple way to show your adjusted Date is just to wrap it in a
<Text>A simple view of dateTime: {String(this.state.date)}</Text>
https://snack.expo.io/WGQYSpXip

React native <RNDatePicker> not closing on first try

so i have a component that uses textinput and rndatepicker
it works like this:
1) when textinput is focused datepicker must appear.
2) after selecting date the value of textinput changes to selected date.
my problem is im having to close the modal twice and the other components value changes with the operation on current component.
here is the code
import * as React from 'react';
import {Modal, Platform} from 'react-native';
import {TextInput} from 'react-native-paper';
import RNDatePicker, {Event} from '#react-native-community/datetimepicker';
import moment from 'moment';
interface IProps {
value: string;
onChange: (value: string, date: Date | undefined) => void;
}
const isIOS = Platform.OS === 'ios';
let visible = false;
const DatePicker = ({value, onChange}: IProps) => {
const [isVisible, setVisible] = React.useState(false);
const renderDatePicker = () => {
const datepicker = (
<RNDatePicker
value={value ? moment(value).toDate() : new Date()}
minimumDate={value ? moment(value).toDate() : new Date()}
onChange={(_: Event, date: Date | undefined) => {
onChange(moment(date).format('YYYY/MM/DD'), date);
visible = !visible;
}}
display="calendar"
/>
);
return isIOS ? (
<Modal
transparent
visible={isVisible}
supportedOrientations={['portrait']}
onRequestClose={() => {
setVisible(false);
}}>
{datepicker}
</Modal>
) : (
datepicker
);
};
return (
<>
<TextInput
value={value ? moment(value).format('YYYY/MM/DD') : ''}
onFocus={() => {`
setVisible(!visible);
visible = true;
}}
onBlur={() => {
setVisible(false);
visible = false;
}}
keyboardAppearance="dark"
style={{backgroundColor: 'transparent'}}
/>
{/* { if(visible) renderDatePicker()} */}
{visible && renderDatePicker()}
</>
);
};
export default DatePicker;
You have to use onChange/onFocus function as per below ...
const onChange = (event, selectedDate) => {
if (selectedDate === undefined) {
setVisible(false);
} else {
setDate(currentDate);
}
};
ref. https://github.com/react-native-community/datetimepicker

Binding redux form input.value to a datetimepicker

I have a react native/redux/redux form setup which is (mostly) working, so everything is hooked up and running.
When I set up a form with an asynchronous update, I get a date field, for which I defined a custom component to be used as <Field> in redux-form.
Here's my component:
import React, { Component } from "react";
import { TouchableOpacity, StyleSheet } from "react-native";
import { Text, theme, Button, Block, Input } from "galio-framework";
import DateTimePicker from "react-native-modal-datetime-picker";
export class DateInputField extends Component {
constructor(props) {
super(props);
this.state = { isDateTimePickerVisible: false };
this.handleChange = this.handleChange.bind(this);
}
showDateTimePicker = () => {
this.setState({ isDateTimePickerVisible: true });
};
hideDateTimePicker = () => {
this.setState({ isDateTimePickerVisible: false });
};
handleChange = date => {
console.log("date->" + date);
this.setState({ isDateTimePickerVisible: false, date: date });
this.props.input.onChange(date);
};
render() {
const { input, meta, ...inputProps } = this.props;
return (
<Block style={styles.container}>
<TouchableOpacity onPress={this.showDateTimePicker}>
<DateTimePicker
date={new Date(input.value)}
cancelTextIOS="Annulla"
confirmTextIOS="Conferma"
isVisible={this.state.isDateTimePickerVisible}
onConfirm={this.handleChange}
onCancel={() => this.setState({ isDateTimePickerVisible: false })}
/>
<Input
color={"black"}
editable={false}
// onTouch={this.showDateTimePicker}
// onFocus={this.showDateTimePicker}
label={this.props.label}
style={styles.input}
placeholder={this.props.placeholder}
value={
this.state.date != undefined
? this.state.date.getDate() +
"/" +
(this.state.date.getMonth() + 1) +
"/" +
this.state.date.getFullYear()
: "gg/mm/aaaa"
}
/>
</TouchableOpacity>
</Block>
);
}
}
export const styles = StyleSheet.create({
container: {},
label: {},
input: { flex: 1, color: "red", padding: 0, height: 50 }
});
and my field:
<Field name={"consignment_date"} label="Fine" component={DateInputField} />
This component works, when I press the field the datepicker shows up with the correct date coming from the connected "model" field connected to it.
Now my problem is I can't figure way an elegant way to update the field value when the field is not updated by a human "onChange" event but the component's state is updated (and subsequently the component is rendered). I tried many combinations of setting the state date field, but I always ended in infinite loops because updating the state would cause a render, and so on.
I tried many Component lifecycle events to put my reading of the input.value and setting it on a state.displayedDate property, but I guess I am missing a very obvious way to do this because of my scarce knowledge of React's dynamics.
Any help is really appreciated.
Posting the solution that works:
import React, { Component } from "react";
import { TouchableOpacity, StyleSheet } from "react-native";
import { Text, theme, Button, Block, Input } from "galio-framework";
import DateTimePicker from "react-native-modal-datetime-picker";
export class DateInputField extends Component {
constructor(props) {
super(props);
this.state = { isDateTimePickerVisible: false }; //no more date in state
this.handleChange = this.handleChange.bind(this);
}
showDateTimePicker = () => {
this.setState({ isDateTimePickerVisible: true });
};
hideDateTimePicker = () => {
this.setState({ isDateTimePickerVisible: false });
};
handleChange = date => {
this.setState({ isDateTimePickerVisible: false });
this.props.input.onChange(date);
};
render() {
const { input, meta, ...inputProps } = this.props;
return (
<Block style={styles.container}>
<TouchableOpacity onPress={this.showDateTimePicker}>
<DateTimePicker
style={styles.label}
date={new Date(input.value)}//date is transformed from input
onDateChange={this.handleChange}
cancelTextIOS="Annulla"
confirmTextIOS="Conferma"
isVisible={this.state.isDateTimePickerVisible}
onConfirm={this.handleChange}
onCancel={() => this.setState({ isDateTimePickerVisible: false })}
/>
<Input
color={"gray"}
editable={false}
enabled={false}
label={this.props.label}
style={styles.input}
placeholder={this.props.placeholder}
value={ //value is transformed to a date, then to the local string representation
input.value !== ""
? new Date(input.value).toLocaleDateString()
: new Date().toLocaleDateString()
}
/>
</TouchableOpacity>
</Block>
);
}
}
export const styles = StyleSheet.create({
container: {},
input: {
flex: 1,
color: "red",
height: 50,
borderWidth: 0,
borderBottomWidth: 1
}
});

How to Pass DatepickerIOS Date Object to Firebase (React Native)

I'm EXTREMELY new at coding, and I took Grinder's course on React Native. I have no idea how to save the datepickerios date object into Firebase. I'm pretty sure something in this code here is incorrect.
Any help would be greatly appreciated. Also, if anyone's looking for a mentee, I'd be grateful for your help. Thanks!
class ScoreForm extends Component {
constructor(props) {
super(props);
this.state = {chosenDate: new Date()};
this.setDate = this.setDate.bind(this);
}
setDate(newDate) {
this.setState({chosenDate: newDate});
}
render() {
return (
<View>
<CardSection>
<Text style={styles.pickerTextStyle}>Enter Date</Text>
</CardSection>
<CardSection>
{/* <Input
label="Date"
placeholder="MM/DD/YY"
value={this.props.date}
onChangeText={value => this.props.scoreUpdate({ prop: 'date', value })}
/> */}
<DatePickerIOS
style={{ flex: 1 }}
mode='date'
date={this.state.chosenDate}
onDateChange={value => this.props.scoreUpdate({ prop: 'date', value })}
/>
</CardSection>
<CardSection>
<Input
label="Score"
placeholder="Add Number"
value={this.props.score}
onChangeText={value => this.props.scoreUpdate({ prop: 'score', value })}
/>
</CardSection>
</View>
);
}
}
const styles = {
pickerTextStyle: {
fontSize: 18,
paddingLeft: 20
}
};
const mapStateToProps = (state) => {
const { date, score } = state.scoreForm;
return { date, score };
};
export default connect(null, { scoreUpdate }) (ScoreForm);
Since I am using Redux, I'm assuming I that I don't want to store it in state, correct? Here is the this.props.ScoreUpdate action:
export const scoreUpdate = ({ prop, value }) => {
return {
type: SCORE_UPDATE,
payload: { prop, value }
};
};

How to press a component via ref?

I'm trying to open the datepicker using onSubmitEditing={() => this.refs.date.press()} but press, onPress or click aren't functions. Which is the function to press a component via ref?
<View>
<Text>Apellido</Text>
<TextInput ref="lastname" onSubmitEditing={() => this.refs.date.click()} onChangeText={(lastname) => this.setState({ lastname })} returnKeyType="next" />
</View>
<View>
<Text>Fecha nacimiento</Text>
<DatePicker
ref="date"
date={this.state.date}
onDateChange={(date) => this.setState({ date })}
/>
</View>
The solution is call to the function that shows the DatePicker internally.
SignUp.js
<View>
<Text>Apellido</Text>
<TextInput ref="lastname" onSubmitEditing={() => this.refs.date.showPicker()} onChangeText={(lastname) => this.setState({ lastname })} returnKeyType="next" />
</View>
<View>
<Text>Fecha nacimiento</Text>
<DatePicker
ref="date"
date={this.state.date}
onDateChange={(date) => this.setState({ date })}
/>
</View>
DatePicker.js
import React, { Component } from 'react';
import moment from "moment";
import {
DatePickerAndroid,
Text,
TouchableWithoutFeedback,
View,
} from 'react-native';
export default class DatePicker extends Component {
constructor(props) {
super(props);
this.state = {
date: props.date,
text: moment(props.date).format('DD/MM/YY'),
maxDate: props.maxDate,
minDate: props.minDate,
};
}
async showPicker() {
try {
const {action, year, month, day} = await DatePickerAndroid.open(
{ date: this.props.date, maxDate: this.props.maxDate, minDate: this.props.minDate }
);
if (action !== DatePickerAndroid.dismissedAction) {
var date = new Date(year, month, day);
this._onDateChange(date);
}
} catch ({code, message}) {
console.warn('Error in example ' + message);
}
}
_onDateChange(date) {
var text = moment(date).format('DD/MM/YY');
this.props.onDateChange(date);
this.setState({
text,
date
});
}
render() {
return (
<TouchableWithoutFeedback onPress={() => this.showPicker()}>
<View >
<Text style={this.props.style}>{this.state.text}</Text>
</View>
</TouchableWithoutFeedback>
);
}
}
DatePicker.defaultProps = {
date: new Date(),
minDate: new Date(1900, 1, 1),
maxDate: new Date(2016, 11, 1)
};