I want to create a form with two MUI Select
components. Conference and division are inter-related. Their relationships are described below.
-
There is a
conference
corresponding to eachdivision
, as shown in theteams
array. When adivision
is selected, the correspondingconference
will be automatically selected. -
There are 3 divisions in each
conference
, as shown in theteams
array. When aconference
is selected, thedivisions
list will be filtered to include divisions corresponding to that conference, e.g. ifWestern
is selected, the divisions list only includesNorthWest
,Pacific
andSouthWest
.
const teams = [
{
"conference": "Eastern",
"division": "Atlantic"
},
{
"conference": "Eastern",
"division": "Central"
},
{
"conference": "Eastern",
"division": "Southeast"
},
{
"conference": "Western",
"division": "Northwest"
},
{
"conference": "Western",
"division": "Pacific"
},
{
"conference": "Western",
"division": "Southwest"
}
]
export default function Demo() {
const [conference, setConference] = useState("Western");
const [division, setDivision] = useState("Pacific");
const [divisions, setDivisions] = useState([...new Set(teams.map(obj => obj.division))]);
const handleConferenceChange = event => {
setConference(event.target.value);
setDivision("");
setDivisions(teams.filter(obj => obj.conference === event.target.value).map(item => item.division));
}
const handleDivisionChange = event => {
setDivision(event.target.value);
setConference(teams.find(obj => obj.division === event.target.value)?.conference);
}
return (
<form>
<Grid container>
<Grid xs={6}>
<Typography sx={{fontWeight: "bold"}}>Conference</Typography>
<Select>
fullWidth
value={conference}
onChange={handleConferenceChange}
>
{[...new Set(teams.map(obj => obj.conference))].map((conference, index) => <MenuItem key={index} value={conference}>{conference}</MenuItem>)}
</Select>
</Grid>
<Grid xs={6}>
<Typography sx={{fontWeight: "bold"}}>Division</Typography>
<Select>
fullWidth
displayEmpty
renderValue={selected => selected?.length === 0 ? <span>-- Select --</span> : selected}
value={division}
onChange={handleDivisionChange}
>
{divisions.map((division, index) => <MenuItem key={index} value={division}>{division}</MenuItem>)}
</Select>
</Grid>
</Grid>
</form>
)
}
I’ve studied the react-hook-form documentation and searched some tutorials on YouTube. None of them cover my use case. Could someone please teach me how my use case can be implemented using react-hook-form?