Build Interdependent Month Dropdowns in React
BehavioralModel answerLast updated
Create two controlled month selector dropdowns with validation logic that prevents selecting invalid date ranges and past months.
You're building a booking form in React that needs month selection functionality. Your task is to implement two connected dropdown menus for selecting months with specific validation rules.
Requirements:
-
Create two month dropdowns that integrate with an existing form structure. Each dropdown should display all twelve months (January through December) as options.
-
Implement validation constraints:
- Neither dropdown should allow selection of months that have already passed (relative to the current month)
- The second dropdown must not allow selection of any month that comes before the month chosen in the first dropdown
- These constraints should be enforced by disabling invalid options in the UI
-
Maintain controlled component patterns: The dropdowns should not manage their own state. Instead, they should receive values through props and report changes through callbacks, allowing the parent component to remain the source of truth.
-
Handle validation in two modes:
- During user interaction: show validation errors when constraints are violated, but allow incomplete selections (only one month chosen)
- On form submission: require both months to be selected and block submission if any validation rule is violated
-
Ensure accessibility: Use native HTML
<select>elements with proper labels, ARIA attributes for invalid states, and clear error messaging connected to form controls. -
Write unit tests that verify:
- Disabled options appear correctly based on current month and interdependencies
- State updates propagate correctly to parent components
- Validation errors display at appropriate times
- Form submission is blocked when validation fails
What to deliver:
- A reusable month selector component
- A form component that integrates two month selectors
- A pure validation function that encapsulates all constraint logic
- Unit tests demonstrating correct behavior
Assume the booking is for the current calendar year only.
Hints
Hint 1
Use a single pure function to encode all validation rules so UI disabled states and error messages stay consistent
Hint 2
Native select elements provide keyboard navigation and screen reader support automatically—avoid rebuilding these behaviors from scratch
Hint 3
Consider how state can become invalid not just through direct selection, but when one dropdown's value changes and invalidates the other
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests your ability to coordinate multiple form inputs with interdependent constraints. The core challenge is keeping validation logic consistent across three places: real-time feedback, disabled option logic, and submit-time checking.
Strategy
Centralize validation in a pure function. Create validateMonths(data, currentMonth, options) that returns an error object. This function runs in two modes:
- Lenient mode during onChange: empty values are acceptable
- Strict mode on submit: both selections required
Derive disabled states from the same rules. Rather than duplicating logic:
- First dropdown disables:
month < currentMonth - Second dropdown disables:
month < max(currentMonth, firstSelection ?? currentMonth)
Use controlled components throughout. The form receives booking state and an onBookingChange callback. It owns no booking data itself, making it compatible with any state management approach (local state, context, Redux, etc.).
Leverage native HTML semantics. <select> elements with <option disabled> give you:
- Keyboard navigation (arrow keys, type-ahead)
- Screen reader announcements
- Focus management
- Standard browser behavior
Add aria-invalid and aria-describedby to connect error messages.
Edge Cases
Same month for both selections: This should be valid. The constraint is "second not earlier than first," so equal values pass (checkOut >= checkIn).
Current month is December: Only December is selectable in both dropdowns.
Changing the first selection invalidates the second: If a user picks June for checkout, then changes checkin to August, the June value becomes invalid even though it wasn't disabled when selected. The validation function catches this and displays an error rather than silently resetting the user's choice.
Null vs zero: Months are 0-indexed (January = 0), so use null for "not selected" to avoid ambiguity. Never use falsy checks like if (!month) because that would treat January as unselected.
Year boundaries: This solution assumes single-year bookings. For a rolling 12-month window, store {year, month} and compare using year * 12 + month. State this assumption explicitly.
Common Mistakes
- Forgetting to re-validate when the first dropdown changes: Disabled options prevent new invalid selections, but don't fix already-invalid state.
- Clearing the second dropdown automatically: This destroys user input. Show an error instead and let them fix it.
- Duplicating validation logic: If disable logic and error logic diverge, the UI becomes confusing.
- Using uncontrolled components: Makes it impossible to integrate with external state or pre-populate from saved data.
Solution
// monthValidation.js
export const MONTH_NAMES = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December',
];
export function validateMonths(
{ firstMonth, secondMonth },
currentMonth,
{ requireBoth = false }
) {
const errors = {};
if (firstMonth == null) {
if (requireBoth) errors.firstMonth = 'Please select the first month.';
} else if (firstMonth < currentMonth) {
errors.firstMonth = 'Cannot select a month in the past.';
}
if (secondMonth == null) {
if (requireBoth) errors.secondMonth = 'Please select the second month.';
} else if (secondMonth < currentMonth) {
errors.secondMonth = 'Cannot select a month in the past.';
} else if (firstMonth != null && secondMonth < firstMonth) {
errors.secondMonth = 'Second month must not be earlier than the first month.';
}
return errors;
}
// MonthSelector.jsx
import { MONTH_NAMES } from './monthValidation';
export function MonthSelector({
id,
label,
value,
onChange,
isMonthDisabled,
error,
}) {
const errorId = `${id}-error`;
return (
<div className="month-selector">
<label htmlFor={id}>{label}</label>
<select
id={id}
value={value ?? ''}
onChange={(e) => {
const val = e.target.value;
onChange(val === '' ? null : parseInt(val, 10));
}}
aria-invalid={error ? 'true' : 'false'}
aria-describedby={error ? errorId : undefined}
>
<option value="">Choose month</option>
{MONTH_NAMES.map((name, index) => (
<option key={index} value={index} disabled={isMonthDisabled(index)}>
{name}
</option>
))}
</select>
{error && (
<div id={errorId} role="alert" className="error-message">
{error}
</div>
)}
</div>
);
}
// ReservationForm.jsx
import { useState } from 'react';
import { MonthSelector } from './MonthSelector';
import { validateMonths } from './monthValidation';
export function ReservationForm({
booking,
onBookingChange,
onSubmit,
currentDate = new Date(),
}) {
const currentMonth = currentDate.getMonth();
const [validationErrors, setValidationErrors] = useState({});
const handleMonthChange = (field, monthValue) => {
const updated = { ...booking, [field]: monthValue };
onBookingChange(updated);
// Validate in lenient mode during interaction
const errors = validateMonths(updated, currentMonth, { requireBoth: false });
setValidationErrors(errors);
};
const handleFormSubmit = (e) => {
e.preventDefault();
// Strict validation on submit
const errors = validateMonths(booking, currentMonth, { requireBoth: true });
setValidationErrors(errors);
if (Object.keys(errors).length === 0) {
onSubmit(booking);
}
};
const minSecondMonth = Math.max(
currentMonth,
booking.firstMonth ?? currentMonth
);
return (
<form onSubmit={handleFormSubmit}>
<MonthSelector
id="first-month"
label="First month"
value={booking.firstMonth}
onChange={(m) => handleMonthChange('firstMonth', m)}
isMonthDisabled={(m) => m < currentMonth}
error={validationErrors.firstMonth}
/>
<MonthSelector
id="second-month"
label="Second month"
value={booking.secondMonth}
onChange={(m) => handleMonthChange('secondMonth', m)}
isMonthDisabled={(m) => m < minSecondMonth}
error={validationErrors.secondMonth}
/>
<button type="submit">Submit Reservation</button>
</form>
);
}
// ReservationForm.test.js
import { render, screen, fireEvent } from '@testing-library/react';
import { useState } from 'react';
import { ReservationForm } from './ReservationForm';
const MAY_2024 = new Date(2024, 4, 15);
function TestWrapper({ initialBooking = { firstMonth: null, secondMonth: null } }) {
const [booking, setBooking] = useState(initialBooking);
const handleSubmit = jest.fn();
return (
<ReservationForm
booking={booking}
onBookingChange={setBooking}
onSubmit={handleSubmit}
currentDate={MAY_2024}
/>
);
}
test('disables past months in both dropdowns', () => {
render(<TestWrapper />);
const firstDropdown = screen.getByLabelText('First month');
const secondDropdown = screen.getByLabelText('Second month');
const aprilOption = Array.from(firstDropdown.options).find(
(opt) => opt.textContent === 'April'
);
expect(aprilOption.disabled).toBe(true);
const mayOption = Array.from(secondDropdown.options).find(
(opt) => opt.textContent === 'May'
);
expect(mayOption.disabled).toBe(false);
});
test('second dropdown disables months before first selection', () => {
render(<TestWrapper />);
const firstDropdown = screen.getByLabelText('First month');
fireEvent.change(firstDropdown, { target: { value: '7' } }); // August
const secondDropdown = screen.getByLabelText('Second month');
const julyOption = Array.from(secondDropdown.options).find(
(opt) => opt.textContent === 'July'
);
const augustOption = Array.from(secondDropdown.options).find(
(opt) => opt.textContent === 'August'
);
expect(julyOption.disabled).toBe(true);
expect(augustOption.disabled).toBe(false);
});
test('shows error when first selection invalidates second', () => {
render(<TestWrapper initialBooking={{ firstMonth: 5, secondMonth: 6 }} />);
const firstDropdown = screen.getByLabelText('First month');
fireEvent.change(firstDropdown, { target: { value: '8' } }); // September
expect(screen.getByRole('alert')).toHaveTextContent(
/must not be earlier than/
);
});
test('blocks submission when validation fails', () => {
const handleSubmit = jest.fn();
render(<TestWrapper />);
const submitButton = screen.getByText('Submit Reservation');
fireEvent.click(submitButton);
expect(screen.getAllByRole('alert')).toHaveLength(2);
expect(handleSubmit).not.toHaveBeenCalled();
});
Complexity
- Time: O(1) per render. Mapping 12 months is constant.
- Space: O(1) beyond the rendered elements.
- Validation: O(1) — simple comparisons.
This structure keeps the validation logic testable, the UI consistent, and the component easy to integrate into larger forms.