Dependent Dropdowns in Next.js Forms
Implement a form with dependent dropdown menus in Next.js, where selections in one dropdown determine the options in another.
import { useState } from 'react';
export default function MyForm() {
const [country, setCountry] = useState('');
const [city, setCity] = useState('');
const handleCountryChange = (event) => {
setCountry(event.target.value);
setCity(''); // Reset the city when country changes
};
// Define dependent options
const countryCityMap = {
'USA': ['New York', 'Los Angeles', 'Chicago'],
'Canada': ['Toronto', 'Vancouver', 'Montreal']
};
const cities = country ? countryCityMap[country] : [];
return (
<form>
<label htmlFor='country'>Country</label>
<select id='country' value={country} onChange={handleCountryChange}>
<option value=''>--Choose a Country--</option>
<option value='USA'>USA</option>
<option value='Canada'>Canada</option>
</select>
<label htmlFor='city'>City</label>
<select id='city' value={city} disabled={!country} onChange={(e) => setCity(e.target.value)}>
<option value=''>--Choose a City--</option>
{cities.map((city) => (
<option key={city} value={city}>{city}</option>
))}
</select>
</form>
);
}
This code snippet creates a Next.js functional component with two dependent dropdowns for selecting a country and a corresponding city. When the country changes, the available cities are updated accordingly, and the city selection is reset.