Examples / Calendars
A month grid
Build a navigable calendar month grid from a YearMonth using locale-aware week boundaries and DateRange iteration.
Try this
- Step backward and forward through months, then click Today to jump back to the current month.
- Call
configure({ locale: 'de-DE' })inapp.jsto shift the grid to Monday-first weeks. - Style weekdays with
day.isWeekday()or step a full year withcurrent.plus(1, 'year').
import { today, weekdayNames, yearMonth } from 'native-dates';
const heading = document.querySelector('#month');
const header = document.querySelector('#weekdays');
const cells = document.querySelector('#days');
let current = yearMonth(today());
header.innerHTML = weekdayNames('short').map((name) => `<span>${name}</span>`).join('');
function render() {
heading.textContent = current.format('long');
const grid = current.start.startOf('week').to(current.end.endOf('week'));
cells.innerHTML = grid.every('day').map((day) => {
const classes = [
day.month !== current.month ? 'outside' : '',
day.isWeekend() ? 'weekend' : '',
day.isToday() ? 'today' : '',
].filter(Boolean).join(' ');
return `<span class="${classes}">${day.day}</span>`;
}).join('');
}
document.querySelector('#prev').addEventListener('click', () => {
current = current.minus(1, 'month');
render();
});
document.querySelector('#today').addEventListener('click', () => {
current = yearMonth(today());
render();
});
document.querySelector('#next').addEventListener('click', () => {
current = current.plus(1, 'month');
render();
});
render();
Starting…
How it works
The calendar state is a single yearMonth(today()) value. Stepping between months takes one call to minus() or plus().
To fill leading and trailing week cells, startOf('week') and endOf('week') expand the month’s bounds to match the active locale’s first day of the week.
Calling every('day') on that range returns every day cell in order, where day.isToday() and day.isWeekend() drive the cell classes directly.