Choosing a Day

Next come the day buttons. Their JSX is ready in DayButtons.jsx, and they need two things: which day is chosen, to show it in gold, and a way to choose another one. But the chosen day is needed by the table too, which shows only that day's showtimes. Two components need the same state, so it goes up to their closest common parent, as in the Sharing State lesson. The table is right in Showtimes, so the state day lives there, "all" at first, and DayButtons gets it in its props, with the function that changes it:

<DayButtons day={day} onSelectDay={setDay} />

Which showtimes the table shows isn't state of its own: it's computed from showtimes and day at each render, and the table makes its rows from shown instead of showtimes:

let shown = showtimes;
if (day !== "all") {
    shown = showtimes.filter((showtime) => showtime.day === day);
}

The gold button. In the project The Cinema in Tailwind, the script moved the class active from button to button. In React, each render works out the classes of every button again from the state. The chosen day's button gets day active, the others just day, with the conditional operator in className:

className={day === "Friday" ? "day active" : "day"}

The three buttons of the days differ only in the day, so they can come from an array with map(): const days = ["Friday", "Saturday", "Sunday"]; above the component, and the All days button on its own, before them. The key of each button is its day.

The classes day and active stay in style.css, as in the Tailwind project. But JSX could also choose between whole sets of Tailwind classes, such as "bg-gold text-night" and "bg-white": the script added a class to the ones a button already had, but the conditional operator gives each button only one of the sets, so they never fight over the background.

Instructions

  1. In Showtimes, add the state day, "all" at first. Import DayButtons and put it under the paragraph, with the props day and onSelectDay as above. In DayButtons.jsx, get both props, and let each button call onSelectDay() with its day: "all", "Friday", "Saturday" or "Sunday". Then let the table show only shown, computed as above. Click Friday: the table has two rows.

  2. Let the gold follow the chosen day: give each button the classes day active when its day is the chosen one, and day otherwise. If you like, make the three buttons of the days with days.map(), as above.