What I want to do is simple, just take input field values and do something with them by clicking button.
function TableFooterPanel() {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const sampleMethod = (x, y) => {
console.log(x y)
}
return (
<>
<Card className='buttonFooter'>
<Form className='buttonFooter'>
<input type="text" placeholder="First Name" defaultValue={firstName} onClick={setFirstName}></input>
<input type="text" placeholder="Last Name" defaultValue={lastName} onClick={setLastName}></input>
<Button onClick={() => sampleMethod(firstName, lastName)}>Add</Button>
</Form>
</Card>
</>
);
}
export default TableFooterPanel;
Generally examples for that is done with separate handleChange() methods for each input field but I don't want to make separate functions for each so I though to use useState. How can I call the sampleMethod with these parameters ? I could not update values properly with useState.
CodePudding user response:
if you use input field as text, you need onChange :
<input type="text" placeholder="First Name" defaultValue={firstName} onChange={e => setFirstName(e.target.value)}></input>
That way the text that you typing in the input will save in the state.
CodePudding user response:
You can use FormData.
Another suggestion from me is to add an onSubmit event to the form. It's more convenient.
The button should be type="submit"
. When the user clicks on it the form's onSubmit
event will fire.