I'm using Material UI, React.
I have data from a text field and data from a drop down select which I would like 'submitted' with a click of a button
Here is the code with alot of the styling fluff removed so it isn't a wall of text:
const MassInput = styled(TextField)({
...
const UnitOfMeasurement = styled(Autocomplete)({
...
const Button2 = styled(Button)({
...
return(
<Box sx={{}}>
<Grid container>
<Grid item>
<Box>
<Box sx={{fontSize: '24px'}}>Settings</Box>
</Box>
</Grid>
<Grid item>
<CloseIcon2/>
</Grid>
</Grid>
<Grid container>
<Grid item xs={12} sm={12} md={12} lg={12} xl={12}>
<MassInput
variant= 'standard'
disablePortal
id="combo-box-demo"
sx={{ width: '100%', input: {color: '#d4e1ed'} }}
placeholder='Enter Your Key'
/>
</Grid>
</Grid>
<Grid container>
<Grid item xs={12} sm={12} md={12} lg={12} xl={12}>
<FormControl fullWidth>
<UnitOfMeasurement
disablePortal
defaultValue={{ label: 'Kilogram', value: 10 }}
id="combo-box-demo"
options={unitsOfMeasurement}
sx={{ width: '100%', input: {color: '#d4e1ed'} }}
ListboxProps={{
className: "myCustomList",
}}
/>
</FormControl>
</Grid>
</Grid>
<Grid container>
<Grid item>
<Box>
<Button2 sx={{width: '90%'}} onClick={handleClose}>
Save Settings
</Button2>
</Box>
</Grid>
</Grid>
</Box>
)
This component receives variables 'key' and 'units' whos state I would like to update on the form submit. So essentially when the Save Settings button is hit:
The TextField input should be used to update the state of 'key' by using 'setKey'. And similarly for the units dropdown select, Depending on the option that text is used to update the state of 'units' using 'setUnits'
function Settings2({key, setKey, units, setUnits}) {
I'm having trouble grasping how I would use FormControl component to accurately capture the 2 pieces of data, and how I can update variable state as a resolution of the form submit. Thank you!!
CodePudding user response:
this is from my experience using react, you can use onChange on the field text then put the value into the state.
and then to post the data you can use onClick on the button to trigger a function that post the data with the endpoint that you have.
CodePudding user response:
You need to create state for values from both form elements Example:
[dropdownElement, setDropdownElement] = useState(initialValue)
[inputElement, setInputElement] = useState(initialValue)
You need to use onChange event handler in fields to set the respective states of the form value. Example:
<select onChange={(e) => setDropdownElement(e.target.value)}......>
<option>.....</option>
.....
</select>
You can then use onClick event handler to: a. get the state, b. construct a body Object for post request c. Send the constructed body Object in a Post request to the server. Example
<button type='submit' onClick = {() => {
const postObject = {
dropdownValue: dropdownElement
inputValue: inputElement
}
//.....API POST.....
}
}> Submit </button>