-
-
Notifications
You must be signed in to change notification settings - Fork 535
Recipes
Wojciech Maj edited this page May 11, 2020
·
6 revisions
import React, { useState } from 'react';
import Calendar from 'react-calendar';
function MyApp() {
const [value, setValue] = useState(new Date());
function onChange(nextValue) {
setValue(nextValue);
}
return (
<Calendar
onChange={onChange}
value={value}
/>
);
}import React, { useState } from 'react';
import Calendar from 'react-calendar';
const disabledDates = [tomorrow, in3Days, in5Days];
function tileDisabled({ date, view }) {
// Disable tiles in month view only
if (view === 'month') {
// Check if a date React-Calendar wants to check is on the list of disabled dates
return disabledDates.find(dDate => isSameDay(dDate, date));
}
}
function MyApp() {
const [value, setValue] = useState(new Date());
return (
<Calendar
onChange={onChange}
value={date}
tileDisabled={tileDisabled}
/>
);
}If you need to support a dynamic list of disabled dates, you can move tileDisabled function to MyApp function body. Use useCallback for optimal performance and update tileDisabled function only if necessary.
The way you compare dates (isSameDay) is up to you. For example, you can use date-fns:
import { differenceInCalendarDays } from 'date-fns';
function isSameDay(a, b) {
return differenceInCalendarDays(a, b) === 0;
}import React, { useState } from 'react';
import Calendar from 'react-calendar';
const datesToAddClassTo = [tomorrow, in3Days, in5Days];
function tileClassName({ date, view }) {
// Add class to tiles in month view only
if (view === 'month') {
// Check if a date React-Calendar wants to check is on the list of dates to add class to
if (disabledDates.find(dDate => isSameDay(dDate, date))) {
return 'myClassName';
}
}
}
function MyApp() {
const [value, setValue] = useState(new Date());
return (
<Calendar
onChange={onChange}
value={date}
tileClassName={tileClassName}
/>
);
}If you need to support a dynamic list of disabled dates, you can move tileClassName function to MyApp function body. Use useCallback for optimal performance and update tileClassName function only if necessary.