How to get the selected date in Calendar Picker on react native? - react-native

am using react-native-calendar-picker library.trying to get the selected date but i receive previews date.
onDateChange (date) {
this.setState({ date: date });
}
<CalendarPicker selectedDate={this.state.date}
onDateChange=(date)=>this.onDateChange(date)}}/>

I would recommend to use react-native-calendar
You can get it from here : https://github.com/christopherdro/react-native-calendar
Usage Example :
<Calendar
scrollEnabled={true}
showControls={true}
titleFormat={'MMMM YYYY'}
dayHeadings={['Sun', 'Mon', 'Tue', 'Wed', 'Thu','Fri','Sat']}
monthNames={['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']}
prevButtonText={'Prev'}
nextButtonText={'Next'}
onDateSelect={(date) => this.onDateChange(date)}
onTouchPrev={this.onTouchPrev}
onTouchNext={this.onTouchNext}
onSwipePrev={this.onSwipePrev}
onSwipeNext={this.onSwipeNext}
eventDates={this.state.events}
customStyle={{day: {fontSize: 15, textAlign: 'center', color: '#4c4b4b'}}}
weekStart={1}
/>

Related

Is there any React Native Date Range picker with date blocking

I am building a booking system using react native, but I am not able to find a Date Range Picker that enables me to block the reserved dates as shown in the following picture.
blocking dates on a calendar
Is there any component that does this job ??
I would preferer functional component if there is any
Try react-native-calendars.
Usage:
const school = {key:'school', color: 'orange', selectedDotColor: 'blue'};
const canteen = {key:'canteen', color: 'blue', selectedDotColor: 'blue'};
const rooms = {key:'rooms', color: 'green'};
<Calendar
markedDates={{
'2017-10-25': {dots: [school, canteen, rooms], selected: true, selectedColor: 'red'},
'2017-10-26': {dots: [canteen, rooms], disabled: true}
}}
markingType={'multi-dot'}
/>

React Native conditionally setting state

I have an array of "favorite" listings per user. I want to set a state variable depending on if it is rendering a favorite item or a regular (non-favorite) item. This is a little heart icon that is either filled or unfilled. It is incorrectly setting the state on first render. Correctly sets it after refresh.. I'm doing something wrong and have tried many things to no avail so if someone could just look at this code and tell me if you see any glaring flaws. If not then I will look elsewhere for the problem.
Behavior when app loads: I am doing console.log just after the state is set to show whether it's a favorite or not, and the contents of the favorite state variable (an image url, but in the console it shows it as either 21 for non-fav, or 22 for a fav). I can see that it is correctly pulling the array of favorites, and correctly identifying those that are and are not favorited (1 means its a favorite). It is however not setting the state variable correctly. Furthermore, it IS setting it correctly for only some of the listings. Currently I have all listings marked as a favorite, and it only messes up the first 10. After that they all set right. MORE bizarre, is upon refreshing the screen, it correctly sets all of them.
MainHeader.js (pulling data from db, setting initial array of favorite listings, and passing it to the messagesScreen component)
const [favsArray, setFavsArray] = useState("");
useEffect(() => {
lookupUser()
.then((snapshot) => {
if (snapshot.hasChildren()) {
snapshot.forEach(function(childSnapshot) {
let favs = childSnapshot.child("favorites").val();
setFavsArray(favs);
})
}
})
.catch((error) => {console.error('Error:', error)});
}, []);
return (
<NavigationContainer>
<View style={styles.headerContainer}>
<Image
style={styles.image}
source={require("../assets/newheader4.png")}
/>
</View>
<Tab.Navigator
tabBarOptions={{
activeTintColor: "blue",
inactiveTintColor: "black",
style: {},
tabStyle: {
width: "auto",
backgroundColor: "#e0d5f3",
borderTopWidth: 3,
borderBottomWidth: 3,
borderRightColor: "gray",
},
labelStyle: {
fontSize: 14,
fontWeight: "bold",
},
scrollEnabled: true,
}}
>
<Tab.Screen name="All Deals" children={()=><MessagesScreen favsArray={favsArray} setFavsArray={setFavsArray}/>} />
</Tab.Navigator>
</NavigationContainer>
MessagesScreen, receives favsArray and renders a FlatList with component Card which it feeds favsArray to.
<FlatList
data={messagesShow}
keyExtractor={(messagesShow) => messagesShow.id.toString()}
renderItem={({ item }) => (
<Card
price={item.currentPrice}
title={item.title}
image={item.image}
posted={item.postedDate}
discAmount={item.discountAmount}
discType={item.discType}
expiration={item.expiration}
promoCode={item.promoCode}
affLink={item.amzLink}
indexStore={item.indexStore}
store={item.store}
favsArray = {favsArray}
/>
)}
ItemSeparatorComponent={ListItemSeparator}
contentContainerStyle={styles.messagesList}
refreshing={refreshing}
onRefresh={() =>
db.ref('deals').once('value', (snapshot) =>{
let testData = [];
snapshot.forEach((child)=>{
// if (child.val().hasOwnProperty('title')){
testData.push({
id: child.key,
title: child.val().hasOwnProperty('title') ? child.val().title : 'NA',
currentPrice: child.val().price,
discountAmount: child.val().discAmt,
discType: child.val().discType,
promoCode: child.val().promoCode,
expiration: child.val().expDate,
postedDate: child.val().postDate,
image: { uri: child.val().imageLink},
amzLink: child.val().affLink,
category: child.val().category,
indexStore: child.val().indexStore,
store: child.val().store
})
// }
checkMessages(testData);
})
})
.then()
.catch((error) => {console.error('Error:', error)})
}
/>
Card component, this is in a FlatList where favsArray is passed as a prop (correctly verified by console), along with the individual listing data. If it finds the listing in the fav array, it should set to HeartFilled (1), if not set to HeartEmpty (0).
let test = [];
test = favsArray.split(',');
let isFav = 0;
let found = test.find(function (element) {
return element == indexStore;
});
if (found != undefined){
isFav = 1;
}
const [heartFilled, setHeartFilled] = useState( isFav == 1 ? require('../assets/heartFilled.png') : require('../assets/heartEmpty.png'));
console.log(isFav + ' ' + heartFilled);
Looking at my console, you can see it correctly shows each listing as a favorite, but for the first 10 listings it sets the state to the wrong image (21, shown in red). These should all be 22.

react-native multi select change select text color

I am new to react-native and i am trying to add multi selection component to my app
my code is as follows:
<SectionedMultiSelect
items={this.state.days}
uniqueKey="id"
hideSearch={true}
subKey="day"
selectText="Select Days"
selectToggle={{ color: '#f79334' }}
showDropDowns={true}
readOnlyHeadings={true}
onSelectedItemsChange={this.onSelectedItemsChangeHomeRepair}
selectedItems={this.state.selectedDaysHomeRepair}
showChips={false}
theme = {
{
Colors:{
selectToggleTextColor:'#053075',
text:'#053075'
}
}
}
/>
does anyone know how to apply color to "Select Days" text. thanks
You could use the renderSelectText prop and pass your own text component with your custom styles.
<SectionedMultiSelect
items={this.state.days}
uniqueKey="id"
hideSearch={true}
subKey="day"
renderSelectText={() => <Text style={{ color: 'red', fontSize: 24 }}>Select Days</Text>}
selectToggle={{ color: '#f79334' }}
showDropDowns={true}
readOnlyHeadings={true}
onSelectedItemsChange={this.onSelectedItemsChangeHomeRepair}
selectedItems={this.state.selectedDaysHomeRepair}
showChips={false}
theme = {
{
Colors: {
selectToggleTextColor:'#053075',
text:'#053075'
}
}
}
/>
Have a look at how this can be used in the example here.

How to set date on scrolling the Week Calendar in react-native-calendars package

I am trying to use WeekCalendar from react-native-calendars package. I am able to view the WeekCalendar and scroll it. However, I want that on horizontal scroll - the currentDate should be updated to date in that current week and should be updated on the UI. How do I go about this?
I was able to find a solution for onclick but I want on scrolling the current date should be a date from that current week.
<WeekCalendar
firstDay={1}
current={selectedDateOfTheWeek}
onDayPress={(day, localDay) => {
changeSelectedDateFromCalendar(day.dateString, false);
}}
hideExtraDays={false}
pastScrollRange={24}
futureScrollRange={24}
markedDates={{
[selectedDateOfTheWeek]: {
selected: true,
selectedColor: "#8660ce"
}
}}
/>
selectedDateOfTheWeek stores the date in 'YYYY-MM-DD' format. I am using Redux to manage the state.
wrap your week calendar with <CalendarProvide and use onDateChanged event
<CalendarProvider
date={this.state.selectedDate.dateString}
onDateChanged={this.onDateChanged}
markedDates={{
...this.state.markedDates,
[this.state.selectedDate.dateString]: {
selected: true,
},
}}
>
<WeekCalendar
testID={testIDs.weekCalendar.CONTAINER}
hideDayNames={true}
firstDay={1}
dayComponent={this.renderDateWeek}
theme={calendarThemes}
calendarWidth={screenWidth}
allowShadow={false}
markedDates={{
...this.state.markedDates,
[this.state.selectedDate.dateString]: {
selected: true,
},
}}
pastScrollRange={(new Date().getFullYear() - 1900) * 12}
futureScrollRange={(2099 - new Date().getFullYear()) * 12}
style={[styles.calendar, { paddingBottom: 20, paddingLeft: 0, paddingRight: 0 }]}
onDayPress={(date) => this.changeDate(date.dateString)}
/>
</CalendarProvider>

open a componet by click on text in react native

I want to open a calendar component when I click on a text.
<Text onPress={_onPressButton}>Select date</Text>
var _onPressButton = () => {
return (
<DatePicker />
)
};
UPDATE :
I found the answer here
https://github.com/xgfe/react-native-datepicker/issues/73#issuecomment-278840899
You have to keep a ref to the data picker component and call the method "onPressDate" using the date picker ref.
Note: #Nima i am answering this according to the package you are using (
https://github.com/xgfe/react-native-datepicker)
Check the snippet below
In constructor:
this.startDatePicker = this.updateRef.bind(this, "startDate");
updateRef method:
updateRef(name, ref) {
this[name] = ref;
}
DatePicker component:
<DatePicker
showIcon={false}
ref={this.startDatePicker}
date={this.state.startDate}
mode="date"
placeholder="select date"
format="DD-MM-YYYY"
minDate={new Date()}
confirmBtnText="Confirm"
cancelBtnText="Cancel"
onDateChange={date => {
global.consoleLogger('the current date selection', date);
}}
/>
Call this method on click of the text or button:
openStartDatePicker = () => {
this.startDate.onPressDate();
}
Hope this helps.
What date picker do you use for it? Because i guess its not DatePickerAndroid or DatePickerIOS from react-native library. I think you use react-native-datepicker. It creates new component in view so not sure if you are able to open it from different place (on text click). In my opinion React Native Picker is better because has method Picker.show() so you can display it on text press.
link to documentation: https://github.com/beefe/react-native-picker*
You have to init picker with properdata passed in array.
const initPicker = ( onConfirm, onCancel, dateFrom, dateTo ) => {
Picker.init({
pickerData: createLastDates(dateFrom, dateTo),
pickerConfirmBtnText: "Confirm",
pickerCancelBtnText: "Cancel",
pickerTitleText: '',
pickerConfirmBtnColor: [255, 0, 0, 1],
pickerCancelBtnColor: [150, 150, 150, 1],
pickerBg: [255, 255, 255, 1],
pickerToolBarBg: [200, 200, 200, 1],
onPickerConfirm: onConfirm,
onPickerCancel: onCancel,
});
};
and then on first click you have to use this function to initialize picker and then show picker with Picker.show();
<Text
onPress={() => {this.onPressDate()}}>
Your Text
</Text>