Display current date calendar react? - reactjs

I am building a calendar, it has 53 weeks from (12-30-2019 -> 03-01-2021). How when the app first loads it display current date.
// the function display dates
export default function RenderDates(props) {
const dates_ = [];
const startDate = moment('12-29-2019', 'MM-DD-YYYY');
// display date in week
for(let i = 1; i <= 53*7; i++) {
dates_.push(
<Date>
<ContentDate>
<ShortDate>{moment.weekdaysShort()[i%7]}</ShortDate>
<span>{startDate.add(1,'days').get('Date')}</span>
</ContentDate>
</Date>
)
}
return dates_;
}
demo: https://codesandbox.io/s/github/Kalipts/scroll_calendar?file=/src/components/RenderDates.js

You can assign unique id to every date box and then focus today's box
https://codesandbox.io/s/quirky-leavitt-w2x3w
export default function RenderDates(props) {
const dates_ = [];
const startDate = moment("12-29-2019", "MM-DD-YYYY");
useEffect(() => {
const today = moment().format("YYYY-MM-DD");
console.log('today', today);
const node = document.getElementById(today);
if (node) {
node.setAttribute("tabindex", "-1");
node.focus();
node.removeAttribute("tabindex");
}
}, []);
for (let i = 1; i <= 53 * 7; i++) {
const date = startDate.add(1, "days");
dates_.push(
<Date id={date.format("YYYY-MM-DD")}>
<ContentDate>
<ShortDate>{moment.weekdaysShort()[i % 7]}</ShortDate>
<span>{date.get("Date")}</span>
</ContentDate>
</Date>
);
}
return dates_;
}

I just changed a bit your codesandbox to make it work and here is the link: https://codesandbox.io/s/vibrant-worker-b2xhq?file=/src/App.js
Basically what I did was:
On your RenderDates component I check for the current date and added an id to the Date component if that date was the current one.
On App component (It could be on RenderDates component) I added a useEffect to run once the component is mounted that getElementById using the id on date and scrollIntoView.
It is very simple and works well! :)

Related

Creating a reusable date formatter in React

I've been struggling to create a reusable function that I can call on dates in my data. The goal is to take any date given, determine if it has just a date, or date and time, then return the data in the appropriate format.
I've been using moment to format things, but am not sure how to actually call this function on the data. I'm very new to React
Here is what I've got so far:
import moment from "moment";
const FormatDate = (dateObject) => {
var dateMutant = dateObject;
var dateMutated = "";
function justDate() {
//formats just a date
dateMutated = moment.utc(dateMutant).format("MM-DD-YYYY");
}
function dateTime() {
//formats a date and time
dateMutated = moment.utc(dateMutant).format("MM-DD-YYYY hh:mm:a");
}
console.log(dateMutated);
return dateMutated;
};
export default FormatDate
I am attempting to call it in a page like this:
React.useEffect(() => {
var testDate = '';
if (allCommentsFetch) {
setAllCommentsLoading(true);
axios
.get(`###API Hook##`)
.then(response => {
let comments = response.data;
comments.forEach(commentfield => {
if (commentfield != null) {
commentfield['commentTimestamp'] = moment.utc(commentfield.commentTimestamp).format('YYYY-MM-DD hh:mm:ss');
testDate = FormatDate(commentfield.commentTimestamp).justDate();
} else {
comments[commentfield] = 'N/A'
}
})
but am getting an error that Object(...)(...).justDate is not a function.
you can write it in a better and cleaner way, first of all, you have not to write your module names in PascalCase, getFormattedName will be a better choice! the second thing is that you are using var... avoid that.
the only thing you have to change in the format function is a format template... and as i see you have only two option (justDate and dateTime) in this case, so let's write it again:
const getFormattedDate = ({ dateObject, includeTime }) => {
const dateFormat = includeTime ? 'MM-DD-YYYY hh:mm:a' : 'MM-DD-YYYY';
return moment.utc(dateObject).format(dateFormat);
};
and about the error you got: (but am getting an error that Object(...)(...).justDate is not a function) the problem is that you didn't return justDate from the FormatDate function.

How to dynamically disable days in react datepicker

I am using React DatePicker .I want to disable days in date picker. I am able to doing so by passing day number like below so Monday Tuesday and Saturday get's disabled.But how do I achieve this dynamically? I am able to form array like this
var notAvailableDays=[1,2,6] // which should disable these days. How do I return this at once?
const isWeekday = (date) => {
const day = date.getDay(date);
return day !== 1 && day !== 2 && day !== 6;
}
;
You can do an array lookup like this
const notAvailableDays = [1,2,6];
const isDisabled = (date) => {
const day = date.getDay(date);
return notAvailableDays.includes(day);
}

Angular not detecting change to first element in array

I'm trying to display a list of dates for the current week in an Angular app. I want to allow users to view previous weeks at the click of a button, so I'm using an Observable to update the array of dates, and attempting to display the updated array.
All items are updated in the view, except for the first item in the array. Plunker example here
I've tried using *ngFor and the async pipe, as well as explicitly creating elements for each item in the array (like below). Both have the same issue. I'm struggling to find a solution.
//our root app component
import {Component, NgModule, VERSION} from '#angular/core'
import {BrowserModule} from '#angular/platform-browser'
import 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
#Component({
selector: 'my-app',
template: `
<button (click)="previousWeek()">Prev Week</button>
<div>{{dates[0]}}</div>
<div>{{dates[1]}}</div>
<div>{{dates[2]}}</div>
`,
})
export class App {
name:string;
dates: Date[];
public $datesSource: Observable<Date[]>;
private datesSource: Subject<Date[]>;
constructor() {
this.datesSource = new Subject<Date[]>();
this.datesSource$ = this.getDatesWithObservable();
this.datesSource$.subscribe((dates) => {
console.log(dates);
this.dates = dates;
})
this.setDates(new Date());
}
setMonday(date: Date): Date {
const day = date.getDay() || 7;
if (day !== 1) {
date.setHours(-24 * (day - 1));
}
return date;
}
setDates(date: Date): void {
const dates = [
new Date(),
new Date(),
new Date(),
new Date(),
new Date(),
new Date(),
new Date()
];
const monday = this.setMonday(date);
dates[0] = monday;
const mondayDate = monday.getTime();
dates.forEach((date, idx) => {
console.log(idx);
date.setTime(monday.getTime() + (idx * 24 * 60 * 60 * 1000));
});
this.addDates(dates);
}
addDates(dates: Date[]): void {
this.datesSource.next(dates);
}
getDatesWithObservable(): Observable<Date[]> {
return this.datesSource.asObservable();
}
previousWeek(): void {
const day = this.dates[0].getDay() || 7;
const lastWeek = this.dates[0];
const days = 7;
lastWeek.setTime(lastWeek.getTime() - (days * 24 * 60 * 60 * 1000));
this.setDates(lastWeek);
}
}
try this , i commented the line in the middle and it's working, can you check:
const monday = this.setMonday(date);
//dates[0] = monday;
const mondayDate = monday.getTime();

Angular Scope watch change on filter change (v1.4.3)

I got a wired error
I have directive date picker
I have watch listener while the date change
$scope.$watch('model', function (newDate) {
if (newDate) {
if ($scope.hideDay) {
$scope.dateFields.day = 1;
} else {
$scope.dateFields.day = new Date(newDate).getUTCDate();
}
$scope.dateFields.month = new Date(newDate).getUTCMonth() +1;
$scope.dateFields.year = new Date(newDate).getUTCFullYear();
} else {
if ($scope.hideDay) {
$scope.dateFields.day = 1;
} else {
$scope.dateFields.day = null;
}
$scope.dateFields.month = null;
$scope.dateFields.year = null;
}
});
My weird problem is that I have a search box
<input class="free-txt" ng-model="search.name" placeholder="Free search" />
When I typed in the search box The watch model changed with no reason.
What can be the reason for this bug and how can I fixed it?
Here is the full demo
https://embed.plnkr.co/yGqE33kZNwGz7NaNDOD5/
Select day
Select Month
Open the Year modal than Write in the free text "78"
Select The year
The bug when Typing in the free text the day and month change to null
by default angular $watch watch object by reference
https://docs.angularjs.org/api/ng/type/$rootScope.Scope
objectEquality:
Compare for object equality using angular.equals instead of comparing for reference equality.
(default: false)
try to add a parametre to true for watching object or use watchcollection and give it the variables you need
$scope.$watch('model', function (newDate) {
...
},true );
the directive update the model only when the date is valid :
$scope.checkDate = function () {
$timeout(function () {
var date = rsmDateUtils.checkDate($scope.dateFields);
if (date) {
// the watch is called what date is valid with a year
if ($scope.hideDay) {
$scope.model = $filter('date')(date, 'yyyy-MM');
} else {
$scope.model = $filter('date')(date, 'yyyy-MM-dd');
}
}
});
};

How to change view date dynamically (which is filter event by date time)

I Want to filter event by date but date is pass by normal input type="text" not kendo default datepicker.And display passing date in kendo schduler header But cant not change view date.This is my code.........
$scope.searchEventByDate = function (item) {
var scheduler = $("#scheduler").data("kendoScheduler");
scheduler.view().startDate(item.StartDate);
scheduler.view().endDate(item.EndDate);
scheduler.view(("day"));
$scope.scheduler.dataSource.read();
};
This is my filter param
parameterMap: function (options, operation) {
var popupheight = $(window).height() - 180 + 'px';
$scope.popupWraperForTryout = popupheight;
var scheduler = $("#scheduler").data("kendoScheduler");
if (searchCount != 0) {
if (operation === "read") {
return {
filterByPersonalEvent: $scope._filterParamObj.filterBypersonal,
filterBySignUpRequired: $scope._filterParamObj.filterBySingupRequired,
filterByPaidOrFree: $scope._filterParamObj.filterByPaid,
filterByEventStatus: $scope._filterParamObj.eventStatusId,
filterByEventType: $scope._filterParamObj.eventTypeId,
selectedTeam: $scope._filterParamObj.seasonTeamId,
filterByStartDate: scheduler.view().startDate(),
filterByEndDate: scheduler.view().endDate(),
OrgId: _orgId,
UserTimezone: global.userTimezoneOffset
}
}
}
},
I am so tired.This code is not change in view date.Please help me
Several issues here - the day view shows just one day; you can't set startDate and endDate - just date.
$scope.searchEventByDate = function (item) {
var scheduler = $("#scheduler").data("kendoScheduler");
//scheduler.view().startDate(item.StartDate);
//scheduler.view().endDate(item.EndDate);
scheduler.view("day");
// item.StartDate should be Date object - like scheduler.date(new Date("2013/6/6"));
scheduler.date(item.StartDate);
$scope.scheduler.dataSource.read();
};
If you need to set some explicit date range to filter - you can do it, but still you can't show more than just one day in day view.
$scope.searchEventByDate = function (item) {
var scheduler = $("#scheduler").data("kendoScheduler");
scheduler._myFilterStartDate = item.StartDate;
scheduler._myFilterEndDate = item.EndDate;
scheduler.view("day");
scheduler.date(item.StartDate);
$scope.scheduler.dataSource.read();
};
And in parameter map:
...
return {
filterByStartDate: scheduler.view().startDate(),
filterByEndDate: scheduler.view().endDate(),
myFilterStartDate: scheduler._myFilterStartDate,
myFilterEndDate: scheduler._myFilterEndDate,
OrgId: _orgId,
UserTimezone: global.userTimezoneOffset
};
...

Resources