So I have a following dialog:
<Dialog>
<DialogContent sx={{ display: "flex", flexDirection: "column" }}>
<TextField
id="item-name"
label="Item Name"
/>
<TextField
id="item-description"
label="Item Description"
multiline
/>
</DialogContent>
<DialogActions>
<Button onClick={onAddDialogClose}>Cancel</Button>
<Button onClick={onAddNewItem}>Add Item</Button>
</DialogActions>
</Dialog>
I want to make a REST API call with data from those fields on "Add Item" button click. How do I get those values from <TextField>
s?
CodePudding user response:
You should make your TextFields controlled component
by adding state to them:
const [itemName, setItemName] = useState('')
const [itemDest, setItemDest] = useState('')
const onAddNewItem = () => {
api.call(itemName, itemDest) // or whatever you want
console.log(itemName)
console.log(itemDest)
setItemName('')
setItemDest('')
}
return (
<Dialog>
<DialogContent sx={{ display: 'flex', flexDirection: 'column' }}>
<TextField
id="item-name"
label="Item Name"
value={itemName}
onChange={e => {
setItemName(e.target.value)
}}
/>
<TextField
id="item-description"
label="Item Description"
multiline
value={itemDest}
onChange={e => {
setItemDest(e.target.value)
}}
/>
</DialogContent>
<DialogActions>
<Button onClick={onAddDialogClose}>Cancel</Button>
<Button onClick={onAddNewItem}>Add Item</Button>
</DialogActions>
</Dialog>
)