日本語

How to Display Weekly Plans as a Timetable in React

​​React​CSS Grid,Playwright,TypeScript

To show a week of plans like a timetable, build a CSS Grid with the seven days as columns and times as rows. If each row is 5 minutes, an event from "10:30 to 12:00" can be placed at the correct height by converting its start and end times to row line numbers and writing them in grid-row. Overlapping events are assigned to positions side by side (lanes), and the day column is divided evenly among them. This works well when you want to show meetings and study session events across a whole week, like a weekly calendar view.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx files with tsc, transformed them with esbuild, ran the week calculation and lane assignment in Node.js, and checked the screen by operating Chromium with Playwright. I did not test Firefox, Safari, real smartphones, or screen reader output. Events that cross midnight, all-day events, and drag-to-move operations are not covered.

Timetable screen. At the top are the buttons "Previous week", "This week", and "Next week" and the label "Week from 11/2". On the left are times from 8:00 to 16:00, and on the right are columns from 11/2 (Mon) to 11/5 (Thu). The header for 11/4 (Wed) has a light blue background. On 11/4, three events are side by side at 10:00 (a regular meeting), 10:30 (review), and 11:00 (phone call). Because the column is narrow, the last line of the name of the regular meeting (label in Japanese in the image) is cut off. On 11/5, a 14:00 presentation practice and a 15:00 daily report are stacked on the left, and a 14:30 interview is on the right. The 30-minute daily report is too short for its label, so the lower half of its name is cut off
Monday to Thursday, 8:00 to 16:00, of the test timetable. Overlapping events appear side by side

Get Monday of the week by counting days

The seven days shown in the timetable can be built from one value, the Monday of the week to display, by adding one day at a time. Dates are handled as integers counting the days since January 1, 1970, using Date.UTC. Date.UTC treats the year, month, and day as UTC, so the date does not shift with the browser's time zone.

ts
const DAY = 24 * 60 * 60 * 1000;

// Convert 'YYYY-MM-DD' to the number of days since 1970-01-01 (not affected by time zone)
export function toDay(date: string): number {
  const [y, m, d] = date.split('-').map(Number);
  return Date.UTC(y, m - 1, d) / DAY;
}

// Get the month, date, and weekday (0 is Sunday) from the day number
export function dayParts(day: number) {
  const dt = new Date(day * DAY);
  return { month: dt.getUTCMonth() + 1, date: dt.getUTCDate(), weekday: dt.getUTCDay() };
}

// The Monday of the week that contains the day. Sunday is treated as the end of the previous week
export function mondayOf(day: number): number {
  const { weekday } = dayParts(day);
  return day - ((weekday + 6) % 7);
}

// Convert 'HH:MM' to minutes since 0:00
export function toMinutes(time: string): number {
  const [h, m] = time.split(':').map(Number);
  return h * 60 + m;
}

As described in the getDay() documentation, the weekday number starts at 0 for Sunday. To make a week that starts on Monday, (weekday + 6) % 7 converts the number to "Monday is 0, Sunday is 6", and then the code moves back that many days. If you use a formula that subtracts the weekday number and adds 1, Sunday's number is 0, so the result moves forward one day to the next Monday. These are the results of running this in Node.js.

text
2026-11-02 → 週の月曜 11/2(月)
2026-11-04 → 週の月曜 11/2(月)
2026-11-08 → 週の月曜 11/2(月)
2026-11-09 → 週の月曜 11/9(月)
2026-03-08 → 週の月曜 3/2(月)
2026-11-01 → 週の月曜 10/26(月)
2026-11-08 → 曜日の番号を引いて1を足すと 11/9(月)

The results were the same when I changed the environment variable TZ to Asia/Tokyo, UTC, and America/New_York. For comparison, I also ran new Date('2026-11-08').getDay(), which returned 6 (Saturday) only for America/New_York. As described in the MDN Date documentation, a date-only string is read as midnight UTC, and getDay() returns the weekday in local time, which is the previous evening in New York.

Place events on a grid with 5-minute rows

This is the timetable component. It takes the Monday of the week to display (weekStart) and the time range to show (8:00 to 20:00 by default). The first column is the time, columns 2 to 8 are Monday to Sunday, and the first row is the weekday headers.

tsx
import type { CSSProperties } from 'react';
import { assignLanes } from './lanes';
import { dayParts, toDay, toMinutes } from './week';

export type Plan = { id: string; title: string; date: string; start: string; end: string };

type Props = {
  events: Plan[];
  weekStart: number; // Monday of the week (value from toDay)
  today: number;
  from?: number; // First time shown (minutes)
  to?: number; // Last time shown (minutes)
};

const STEP = 5; // 1 row = 5 minutes
const WEEKDAYS = ['日', '月', '火', '水', '木', '金', '土'];
const hhmm = (min: number) => `${Math.floor(min / 60)}:${String(min % 60).padStart(2, '0')}`;

export function Timetable({ events, weekStart, today, from = 8 * 60, to = 20 * 60 }: Props) {
  const days = Array.from({ length: 7 }, (_, i) => weekStart + i);
  const hours = Array.from({ length: (to - from) / 60 }, (_, i) => from + i * 60);
  // Convert a time (minutes) to the grid line number. Row 1 is the weekday header
  const line = (min: number) => (min - from) / STEP + 2;

  const grid: CSSProperties = {
    gridTemplateColumns: `3.5em repeat(7, minmax(120px, 1fr))`,
    gridTemplateRows: `auto repeat(${(to - from) / STEP}, 4px)`,
  };

  return (
    <div className="tt-scroll">
      <div className="tt" style={grid}>
        {days.map((day, i) => {
          const { month, date, weekday } = dayParts(day);
          return (
            <div
              key={day}
              className={day === today ? 'tt-day today' : 'tt-day'}
              style={{ gridColumn: i + 2, gridRow: 1 }}
            >
              {month}/{date}({WEEKDAYS[weekday]})
            </div>
          );
        })}
        {hours.map((h) => (
          <div key={h} className="tt-hour" style={{ gridColumn: '1 / -1', gridRow: `${line(h)} / span ${60 / STEP}` }}>
            <span>{hhmm(h)}</span>
          </div>
        ))}
        {days.map((day, i) => {
          const spans = events
            .filter((e) => toDay(e.date) === day)
            .map((e) => ({
              id: e.id,
              title: e.title,
              label: `${e.start}〜${e.end} ${e.title}`,
              shown: hhmm(toMinutes(e.start)), // Show the original start time on screen
              // Cut off the part outside the table's time range, and widen to 5-minute units
              start: Math.floor(Math.max(toMinutes(e.start), from) / STEP) * STEP,
              end: Math.ceil(Math.min(toMinutes(e.end), to) / STEP) * STEP,
            }))
            .filter((e) => e.start < e.end);
          return assignLanes(spans).map((e) => (
            <div
              key={e.id}
              className="tt-event"
              style={{
                gridColumn: i + 2,
                gridRow: `${line(e.start)} / ${line(e.end)}`,
                // Overlapping events are placed side by side by dividing the day column into `lanes` equal parts
                width: `calc(${100 / e.lanes}% - 4px)`,
                marginLeft: `calc(${(100 * e.lane) / e.lanes}% + 2px)`,
              }}
              title={e.label}
            >
              <span className="tt-time">{e.shown}</span>
              {e.title}
            </div>
          ));
        })}
      </div>
    </div>
  );
}

Each row is 4px high, so one hour (12 rows) is 48px. For grid-row, you write the line numbers between rows as "start line / end line". The 8:00 line is the second line, just below the header, so line is "minutes after 8:00 ÷ 5 + 2". For an event from 10:30 to 12:00, that gives 32 / 50.

For the time labels, each one-hour element uses gridColumn: '1 / -1' to span all columns, and its top border (border-top) works as a horizontal rule. As described in the CSS Grid specification's section on z-order, grid items without z-index are painted in the order they appear in the HTML. The time labels are written before the events, so where they overlap, the events are painted on top.

These are some of the results from measuring, in Chromium, the distance from the 8:00 line to the top of each event and its height. Every value matched "minutes × 48 ÷ 60" in px.

text
9:00朝の勉強会|列 0|8:00 からの y 48.0px(60分)高さ 48.0px(60分)|列内の左端 2.0px 幅 116.0px(列の 96.7%)
13:00資料づくり|列 1|8:00 からの y 240.0px(300分)高さ 120.0px(150分)|列内の左端 2.0px 幅 116.0px(列の 96.7%)
7:30早朝ラン|列 4|8:00 からの y 0.0px(0分)高さ 48.0px(60分)|列内の左端 2.0px 幅 116.0px(列の 96.7%)
19:00映画|列 5|8:00 からの y 528.0px(660分)高さ 48.0px(60分)|列内の左端 2.0px 幅 116.0px(列の 96.7%)
10:12買い物|列 6|8:00 からの y 104.0px(130分)高さ 32.0px(40分)|列内の左端 2.0px 幅 116.0px(列の 96.7%)

The early morning run from 7:30 to 9:00 was cut off before the table's time range and placed at 8:00 to 9:00. The movie from 19:00 to 21:00 is cut off at 20:00. For times that don't divide evenly into 5 minutes, such as the shopping from 10:12 to 10:48, the start is rounded down and the end is rounded up, widening it to the 10:10 to 10:50 slot. As described in the grid-row documentation, line numbers must be integers, so the times are aligned to 5-minute units. The time shown inside the event comes from shown, built from the original e.start before rounding, so the screen shows "10:12" and "7:30" as the original times. The title attribute includes the end time as well: for the 10:12 shopping event, it shows "10:12〜10:48" followed by the event's title, which is in Japanese in the data.

Assign overlapping events to lanes and place them side by side

If two events are in the same time range on the same day, they overlap in the same cell when nothing is done about it. As noted in the rendering order section above, the event written later hides the earlier one. So the code goes through events in order of start time and places each one in a free "lane" (a vertical track).

ts
// Assign events on the same day to non-overlapping "lanes"
export type Span = { id: string; start: number; end: number };
export type Placed<T> = T & { lane: number; lanes: number };

export function assignLanes<T extends Span>(items: T[]): Placed<T>[] {
  const sorted = [...items].sort((a, b) => a.start - b.start || b.end - a.end);
  const result: Placed<T>[] = [];
  let group: Placed<T>[] = []; // A cluster of events connected by overlaps
  let laneEnds: number[] = []; // For each lane, the end of the last event placed there
  let groupEnd = -Infinity;

  const closeGroup = () => {
    for (const p of group) p.lanes = laneEnds.length;
    result.push(...group);
    group = [];
    laneEnds = [];
  };

  for (const item of sorted) {
    // If the item doesn't overlap any event in the group, close the group here
    if (item.start >= groupEnd) closeGroup();
    // Place it in the leftmost lane that is free (the previous event there has ended)
    let lane = laneEnds.findIndex((end) => end <= item.start);
    if (lane === -1) lane = laneEnds.length;
    laneEnds[lane] = item.end;
    group.push({ ...item, lane, lanes: 0 });
    groupEnd = Math.max(groupEnd, item.end);
  }
  closeGroup();
  return result;
}

lanes is the number of lanes used in the "cluster" that the event belongs to. A cluster is a set of events connected through overlaps, and it ends when an event comes that doesn't overlap any of them. This way, events at separate times are never made narrow. These are the results of the lane assignment on the test data.

text
[11/4] 定例: lane 0/3、レビュー: lane 1/3、電話: lane 2/3、ランチ: lane 0/1
[11/5] 練習: lane 0/2、面談: lane 1/2、日報: lane 0/2
[連続] A: lane 0/1、B: lane 0/1

On November 4, the regular meeting (10:00 to 11:30), review (10:30 to 12:00), and phone call (11:00 to 11:45) overlap each other, so they were split into three lanes. Lunch from 12:30 doesn't overlap any of them, so it forms its own cluster and uses the full width of the column. On November 5, the daily report (15:00 to 15:30) went into lane 0, which is free after the presentation practice from 14:00 to 15:00. Events where one ends exactly when the next starts, like 9:00 to 10:00 and 10:00 to 11:00, are not treated as overlapping, so they are stacked vertically in the same lane.

The lane number is converted to width and margin-left values. According to the CSS Grid specification, percentage margins on a grid item are calculated against the grid area where the item is placed. So with margin-left set to 0%, 33.3%, and 66.7%, each event is offset by one third of the day column's width. Setting the width to one third of the column lets three events sit side by side. The code subtracts 4px from the width and adds 2px to the left margin to leave a gap between neighboring events. In CSS, justify-self: start aligns each event to the left edge of its column.

css
.tt-scroll { overflow-x: auto; }
.tt { display: grid; font-size: 12px; }
.tt-day { padding: 4px 0; text-align: center; border-bottom: 1px solid #9aa5ab; }
.tt-day.today { background: #eefafd; color: #067a98; font-weight: bold; }
.tt-hour { border-top: 1px solid #dde3e6; }
.tt-hour span { display: inline-block; width: 3.5em; padding-right: 4px; text-align: right; color: #5b666c; transform: translateY(-50%); background: #fff; box-sizing: border-box; }
.tt-event {
  justify-self: start;
  box-sizing: border-box;
  overflow: hidden;
  padding: 2px 4px;
  border-left: 3px solid #067a98;
  border-radius: 4px;
  background: #c8f3fa;
  line-height: 1.3;
}
.tt-time { display: block; font-size: 11px; color: #067a98; white-space: nowrap; }

When measured in a 120px column, a 3-lane event was 36.0px wide and placed at 2.0px, 42.0px, and 82.0px from the left edge of the column. A 2-lane event was 56.0px wide and placed at 2.0px and 62.0px.

With three lanes, the names don't fit. In the first image of the article, the name of the regular meeting (label in Japanese) wraps every two characters, and its last line is cut off at the bottom of the event. The title attribute includes the time and name, but the title attribute documentation notes that it can be hard to reach for people using touch-only devices or keyboards. The same page recommends a method that works for those users when a tooltip-like display is needed.

Week switching buttons and smartphone width

The displayed week is stored as the Monday day number in state, and the buttons add or subtract 7 days. The "This week" button goes back to the Monday of the week that contains today. For testing, I fixed today as November 4, 2026, so the results were the same each time.

tsx
// import and the events data are omitted
const TODAY = toDay('2026-11-04');

export function App() {
  const [weekStart, setWeekStart] = useState(() => mondayOf(TODAY));
  const { month, date } = dayParts(weekStart);
  return (
    <main>
      <div className="toolbar">
        <button onClick={() => setWeekStart((d) => d - 7)}>‹ 前の週</button>
        <button onClick={() => setWeekStart(mondayOf(TODAY))}>今週</button>
        <button onClick={() => setWeekStart((d) => d + 7)}>次の週 ›</button>
        <span className="range">{month}/{date} からの週</span>
      </div>
      <Timetable events={events} weekStart={weekStart} today={TODAY} />
    </main>
  );
}

events holds 13 events from November 2 to 9, 2026. These are the results of pressing the buttons with Playwright.

text
次の週 → 11/9 からの週 | 11/9(月) 11/10(火) 11/11(水) 11/12(木) 11/13(金) 11/14(土) 11/15(日) | 予定: 9:00翌週の勉強会 | 今日の列の数: 0
前の週を2回 → 10/26 からの週 | 10/26(月) 10/27(火) 10/28(水) 10/29(木) 10/30(金) 10/31(土) 11/1(日) | 予定の数: 0 | 今日の列の数: 0
今週 → 11/2 からの週 | 予定の数: 12 | 今日の列: [ '11/4(水)' ]

The week from 10/26 to 11/1, which crosses a month boundary, shows its date headers in sequence. The header for today (light blue background) did not appear in the next week or the week two weeks back, and it appeared again on 11/4 (Wed) when I returned with "This week".

The day columns use minmax(120px, 1fr) as a minimum width, so when the area for the timetable is narrower than 882px including the time column, it does not fit. To handle this, I wrapped the grid in an element with overflow-x: auto (.tt-scroll) so only the timetable scrolls horizontally. When I measured with the screen width set to 390px, .tt-scroll had a visible width of 366px and its content was 882px wide, and it could scroll horizontally. The width of the whole page stayed at 390px, and the page itself never shifted sideways.

​Posted by 86