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

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

Related

react hook form multiple control on one Controller

I have a text input component that uses text input from react native paper, I want to make a place autocomplete by calling google place autocomplete API
right now I can display the suggestion but I can't change the text input value with the value of the suggestion that has been clicked
screenshot of component
since I use Controller from react hook form I thought I could use setValue from useForm to change the value but it didn't do anything when I try to call setValue to change textInput value to one of the suggested value
import React from "react";
import { FlatList, StyleSheet, TouchableOpacity, View } from "react-native";
import { Text, TextInput, Colors } from "react-native-paper";
import { Controller, useForm } from "react-hook-form";
import axiosInstance from "services/axiosInstance";
export default React.forwardRef(
(
{
name,
label,
placeholder,
control,
style: addOnStyle,
...props
},
ref
) => {
const { setValue } = useForm();
const [addressList, setAddressList] = React.useState([])
const getAddressList = async (input) => {
if (input == null || input.match(/^ *$/) !== null) {
setAddressList([])
} else {
const response = await axiosInstance.get(
`https://maps.googleapis.com/maps/api/place/autocomplete/json?input=${input}&components=country:us&language=en&key=API_KEY`
)
setAddressList([])
if (response?.data?.status === "OK") {
response?.data?.predictions?.map((item) => setAddressList(addressList => [...addressList, item.description]))
} else {
setAddressList(["Address not found."])
}
}
}
return (
<View style={{ ...styles.viewInput, ...addOnStyle }}>
<Controller
control={control}
name={name}
defaultValue=""
render={({
field: { onChange, onBlur, value, name },
fieldState: { error },
}) => {
return (
<>
<TextInput
label={label}
name={name}
placeholder={placeholder}
onBlur={onBlur}
onChangeText={(val) => onChange(val, getAddressList(val))}
error={!!error?.message}
value={value}
ref={ref}
{...props}
/>
{error?.message ? (
<Text style={styles.textError}>{error?.message}</Text>
) : null}
{addressList.length > 0 ?
<View style={styles.addressListContainer}>
<FlatList
keyExtractor={(_, i) => String(i)}
data={addressList}
renderItem={({ item, index }) => {
return (
<TouchableOpacity
activeOpacity={1}
style={[styles.addressListItem, index==0 ? {borderTopWidth: 0} : {borderTopWidth: 1}]}
onPress={() => {setAddressList([]), setValue(name, item)}}
>
<Text numberOfLines={1}>{item}</Text>
</TouchableOpacity>
)
}}
/>
</View>
: null}
</>
);
}}
/>
</View>
);
}
);
UPDATE Changed the title to match the current question
I think for now my problem is since the control is set from the outside of the component that makes it can't be changed with setValue from inside the component, now I wonder if we could use multiple control on one Controller?
I solve it by changing setValue(name, item) on onPress to onChange(item) it doesn't need another control

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

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}
/>
}

how to use date and time pickers in react native

I created a react native form and I want to add date and time Picker values to the form and the save them to backend. I have tried few libraries but failed.
You can use react-native-modal-datetime-picker
# using npm
$ npm i react-native-modal-datetime-picker #react-native-community/datetimepicker
# using yarn
$ yarn add react-native-modal-datetime-picker #react-native-community/datetimepicker
Example
import React, { useState } from "react";
import { Button, View } from "react-native";
import DateTimePickerModal from "react-native-modal-datetime-picker";
const Example = () => {
const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
const showDatePicker = () => {
setDatePickerVisibility(true);
};
const hideDatePicker = () => {
setDatePickerVisibility(false);
};
const handleConfirm = date => {
console.warn("A date has been picked: ", date);
hideDatePicker();
};
return (
<View>
<Button title="Show Date Picker" onPress={showDatePicker} />
<DateTimePickerModal
isVisible={isDatePickerVisible}
mode="date"
onConfirm={handleConfirm}
onCancel={hideDatePicker}
/>
</View>
);
};
export default Example;
SIMPLE EXAMPLE FOR YOUR PROBLEM
import React, { Component } from "react";
import { View, Text, StyleSheet } from "react-native";
import DateTimePicker from "react-native-modal-datetime-picker";
export default class ExampleClass extends Component {
constructor(props) {
super(props);
this.state = {
isDatePickerVisible: false,
pickedDate: ""
};
}
//Date Picker handling methods
hideDatePicker = () => {
this.setState({ isDatePickerVisible: false });
};
handleDatePicked = date => {
const mdate = date.toString().split(" ");
this.setState({
pickedDate: mdate[1] + " " + mdate[2] + ", " + mdate[3]
});
this.hideDatePicker();
};
showDatePicker = () => {
this.setState({ isDatePickerVisible: true });
};
render() {
return (
<View style={styles.container}>
{/* Your View Here */}
<DateTimePicker
mode="date"
isVisible={this.state.isDatePickerVisible}
onConfirm={this.handleDatePicked}
onCancel={this.hideDatePicker}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
}
});

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

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)
};