Reputation: 149
I am trying to change the date in the items prop for react native calendars. From the docs, it shows that it requires a date string as a key which then requires an array of objects to display for that particular date.
Something like this.
<Agenda
items: {{
'2019-10-12': [],
'2019-10-13': [{}, {}],
'2019-10-14': [{}],
'2019-10-15': []
}}
/>
However, I do not want to hardcode the dates. What I would like is to display the dates of the next week. This is the approach I have tried
I get the date using
new currentDate = new Date();
I pass this date into weekly items to get my weekly items object.
The below function uses two other functions called addDays
and dateToString
to properly render the dates.
const weeklyItems = (date) => {
const day1 = dateToString(addDays(date, 1));
const day2 = dateToString(addDays(date, 2));
const day3 = dateToString(addDays(date, 3));
const day4 = dateToString(addDays(date, 4));
const day5 = dateToString(addDays(date, 5));
const day6 = dateToString(addDays(date, 6));
const currentDate = dateToString(date);
return {
currentDate : [],
day1: [],
day2: [],
day3: [],
day4: [],
day5: [],
day6: []
}
}
addDays
and dateToString
are my helper functions:
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
This function converts a date object into the form 'YYYY-MM-DD' which is what is required by Agenda
function dateToString (date) {
const newString = moment(date).format('YYYY-MM-DD');
return newString.toString()
}
I have checked to see if my dates were correct and they all check out. I also have used currentDate
and day6
as my objects for the minDate
and maxDate
props for Agenda
and they work as expected.
After doing this my Agenda
now looks like this:
<Agenda
minDate = {currentDate}
maxDate = {day6}
selected = {currentDate}
items: {weeklyItems(currentDate)}
renderEmptyDate={() => {return (<View/>);}}
/>
And this makes it stop working. I know that I have empty arrays in my weeklyItems but for now I am just trying to get the dates working and unfortunately they are not. Any help would be appreciated.
Upvotes: 0
Views: 3635
Reputation: 36
I`m on mobile, so i can't run this code...
Try to return your dates object like that:
return {
[currentDate] : [],
[day1]: [],
...
}
Also you can rewrite your weeklyItems functions to iterate from 0 to 6 and dynamically set properties to object which will be returned.
Than in your component:
// somewhere in your js
// const dates = weeklyItems(currentDate)
// const minDate = dateToString(date)
// const maxDate = dateToString(addDays(date, 6))
<Agenda
minDate = {minDate}
maxDate = {maxDate}
selected = {minDate}
items: {dates}
renderEmptyDate={() => {return (<View/>);}}
/>
Upvotes: 2