'Get value of Material-UI Select within form
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>
Solution 1:[1]
You can use onChange. Then set the value, which will then be capturable in your form.
const [ value, setValue ] = useState('');
const handleCreateNewItem = (e) => {
e.preventDefault();
setValue(e.target.value)
};
<FormControl className={classes.formControl}>
<InputLabel id="demo-simple-select-label">Age</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={age}
onChange={handleCreateNewItem}
>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
Solution 2:[2]
When the fields are much, I suggest you use Formik, it makes it simpler just as you said, you can check it out.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Kelechi Ugwu |
