I am trying to get the currently selected value of a Material-UI Select
component within form
component, but I can't figure out what the proper way is, here is what I have tried:
<form onSubmit={handleCreateNewItem}>
<TextField id="name" label="Name" />
...more text fields...
<Select id="typeOfQuantity">
{typesOfQuantities.map((menuItem) => (
<MenuItem value={menuItem}>{menuItem}</MenuItem>
))}
</Select>
<IconButton type="submit">
<DoneIcon />
<Typography variant="h6" gutterBottom>
Add
</Typography>
</IconButton>
</form>
And the handleCreateNewItem
:
const handleCreateNewItem = (e) => {
e.preventDefault();
const { name, typeOfQuantity, ...restOfFormFields} = e.target.elements;
console.log(typeOfQuantity);
};
But typeOfQuantity
is undefined. I am not using a separate onChange, because there are multiple fields on the form.
Do I have to create its own separate onChange
handler and keep its reference? It would probably work, but it seems like a bad way to do it...
I have just tried with a pure html form and select and it works without issues:
const handleCreateNewItem = (e) => {
e.preventDefault();
const { name, typeOfQuantity, ...restOfFields } = e.target.elements;
console.log(name.value);
console.log(typeOfQuantity.value);
};
<form onSubmit={handleCreateNewItem}>
<select id="typeOfQuantity">
{typesOfQuantities.map((menuItem) => (
<option value={menuItem}>{menuItem}</option>
))}
</select>
</form>
question from:
https://stackoverflow.com/questions/65652339/get-value-of-material-ui-select-within-form 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…