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 Demo3() {
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 => {
setConference(teams.find(obj => obj.division === event.target.value)?.conference);
setDivision(event.target.value);
}
const handleSubmit = event => {
event.preventDefault();
const formData = new FormData();
formData.append("conference", JSON.stringify(conference));
formData.append("division", JSON.stringify(division));
console.log("handleSubmit..........", formData)
}
return (
<form onSubmit={handleSubmit}>
<Grid container>
<Grid xs={6}>
<Typography sx={{fontWeight: "bold"}}>Conference</Typography>
<FormControl fullWidth size="small">
<Select
value={conference}
onChange={handleConferenceChange}
>
{[...new Set(teams.map(obj => obj.conference))].map((conference, index) => <MenuItem key={index} value={conference}>{conference}</MenuItem>)}
</Select>
</FormControl>
</Grid>
<Grid xs={6}>
<Typography sx={{fontWeight: "bold"}}>Division</Typography>
<FormControl fullWidth size="small">
<Select
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>
</FormControl>
</Grid>
</Grid>
<Grid xs={12} container justifyContent="center" sx={{mt: 2}}>
<Button type="submit" variant="contained">Submit</Button>
</Grid>
</form>
)
}
In my React app I want to create a form with two MUI Select
components. Initial values of conference and division are retrieved from API call. 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
.
I’ve studied the react-hook-form documentation and searched some tutorials on YouTube. None of them cover my use case. Can react-hook-form be used in my use case?
2