How to dynamically disable days in react datepicker - reactjs

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

Related

How to generate array of string with the weekdays from the current weekday using moment

Want to generate the dynamic array of string with the weekdays as a value inside the array for the list which I am using.
Required:=> If current weekday is Monday then array should be
['today','tomorrow','Wednesday','Thursday','Friday','Saturday','Sunday']
Array should be dynamic based on the current day.
To generate array with the weekday as a string here is the code.
const daysArray = () => {
const weekArray = [...Array(7 - moment().weekday())];
const today = new Date();
return weekArray.map((week, index) => {
const dayName = moment(today)
.add(index, "days")
.calendar()
.split(" at")[0];
const date = moment(today).add(index, "days").format(DATE_FORMAT);
return { value: dayName, name: dayName, date };
});
};
This will generate the array of object with dynamic weekdays inside it. If you will return only dayName then you'll get you're desired result.

How do I disable past dates and future dates using react-calender?

I have tried various ways to implement it but all I could do is disable specifics days in the calendar. I want to disable future date and disable all previous dates from today.
To disable past dates you declare this function :
const tileDisabled = ({ activeStartDate, date, view }) => {
return date < new Date()
}
and then you pass it to you calandar like this :
<Calendar tileDisabled={tileDisabled} />
if you want to disbale all the dates (past and future) your function have to return true.
const [date, setDate] = useState("");
const disablePastDates = () => {
var today = new Date();
var yyyy = today.getFullYear();
var mm = today.getMonth() + 1;
var dd = today.getDate();
var disableDates = yyyy + "-" + mm + "-" + dd;
setDate(disableDates);
};
useEffect(() => {
disablePastDates();
}, []);

How to set date range selection in react JS DateRangePicker?

I am using 'DateRangePicker' component in my react JS application.
I am trying to restrict start date to last 6 month only and difference between
start and end date should not be more than 1 month.
I wrote following code
isOutsideRange = (day) => {
if (day > moment()) return true;
else if (this.state.startDate) {
if (day > moment(this.state.endDate)) return true;
if (day < moment().subtract(6, 'months')) return true;
else return false;
} else if (this.state.endDate) {
if (day > moment(this.state.endDate)) return true;
if ((moment(this.state.endDate) > (moment(this.state.startDate).subtract(1, 'month')))) return true;
else return false;
}
}
and here is the UI code
<DateRangePicker
startDate={this.state.startDate}
startDateId="validFromDate"
endDate={this.state.endDate}
endDateId="validToDate"
onDatesChange={({ startDate, endDate }) =>
this.handleValidDatesChange(startDate, endDate)
}
focusedInput={this.state.ofrFocusedInput}
onFocusChange={(ofrFocusedInput) => this.setState({ ofrFocusedInput })}
isOutsideRange={(e) => this.isOutsideRange(e)}
showDefaultInputIcon={true}
small={true}
minimumNights={0}
hideKeyboardShortcutsPanel={true}
showClearDates={true}
min={this.maxDate}
shouldDisableDate={({ startDate }) => this.disablePrevDates(startDate)}
// minDate={subDays(new Date(), 10)}
displayFormat={() => "DD/MM/YYYY"}
/>;
I tried to debug but it is not working.
Can someone suggest the solution ?
To check if a moment is between two other moments, optionally looking at unit scale (minutes, hours, days, etc), you should use:
moment().isBetween(moment-like, moment-like, String, String);
// where moment-like is Moment|String|Number|Date|Array
For instance, if you need to check today - 6months <= someDate <= today, you would use something like:
// returns TRUE if date is outside the range
const isOutsideRange = date => {
const now = moment();
return !moment(date)
.isBetween(now.subtract(6, 'months'), now, undefined, '[]');
// [] - match is inclusive
}
For more details, please check Is Between docs. This method is very flexible, for instance, you can have exclusive or inclusive match.
Now, the second condition. If you would like to check if endDate - startDate <= 1 month, you can play with moments as well to achieve this.
// so if you add 1 month to your startDate and then your end date
// is still before the result or the same - you can say the duration
// between them is 1 month
const lessThanMonth = (startDate, endDate) => {
return endDate.isSameOrBefore(moment(startDate).add(1, 'months'));
}
if (day.isAfter(moment()) ||
!day.isAfter(moment().subtract(6,'months'))) return true;

Display current date calendar react?

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! :)

how can I get every day of the month except Friday with Moment.js?

Can someone help me ? I'm trying to get all the days of the month except Friday to disable all this days in a date picker but I can't figure out, how to proceed. I'm looking for the solution for a while now...
So I need an array of Moment to disable them in the date picker.
Here is the date picker.
Thank's for your time and sorry for my bad english !
Without extending moment you can try:
let fridaysInMonth = [];
const monthDate = moment().startOf('month');
const daysInMonth = monthDate.daysInMonth();
for(let i=0; i< daysInMonth; i++){
if (monthDate.day() === 5){
const currFridayDate = moment(monthDate);
fridaysInMonth.push(currFridayDate);
}
monthDate.add(1, 'day');
}
Or extend moment and use moment-range:
const month = moment();
const range = moment().range(moment(month).startOf('month'), moment(month).endOf('month'));
const days = range.by('days');
const fridaysInMonth = days.filter(currDay => currDay.day() === 5);

Resources