I have a button and 2 input field and I am sending these input field values to backend. etc doing some operations. After doing operations in addCustomer function, I want to reset input fields but it is not working. Here is the code:
JavaScript
x
35
35
1
function TableFooterPanel(props) {
2
3
const [firstName, setFirstName] = useState('');
4
const [lastName, setLastName] = useState('');
5
6
const addNewCustomer = async (name, surname) => {
7
await service.addCustomer(name, surname);
8
props.funcParam();
9
setFirstName('');
10
setLastName('');
11
}
12
13
var isButtonDisabled = false;
14
15
(firstName.length <= 3 || lastName.length <= 3) ? isButtonDisabled = true : isButtonDisabled = false;
16
17
return (
18
19
<>
20
<Card className='buttonFooter'>
21
<Form className='buttonFooter'>
22
<input type="text" placeholder="First Name" defaultValue={firstName} onChange={e => setFirstName(e.target.value)}></input>
23
<input type="text" placeholder="Last Name" defaultValue={lastName} onChange={e => setLastName(e.target.value)}></input>
24
<Button disabled={isButtonDisabled} onClick={() => addNewCustomer(firstName, lastName)} className='addButton'>Add</Button>
25
<label hidden={!isButtonDisabled} className='labelStyle'>Field lengths must be at least 4 character</label>
26
</Form>
27
</Card>
28
29
</>
30
31
);
32
33
}
34
export default TableFooterPanel;
35
Here everything is working good except
JavaScript
1
3
1
setFirstName('');
2
setLastName('');
3
they are not resetting or setting to another value. What is the reason for that and how can I achieve it ?
Advertisement
Answer
The problem is that you’re setting the defaultValue prop and not the value prop.
JavaScript
1
3
1
<input type="text" placeholder="First Name" value={firstName} onChange={e => setFirstName(e.target.value)} />
2
<input type="text" placeholder="Last Name" value={lastName} onChange={e => setLastName(e.target.value)} />
3
From docs: https://reactjs.org/docs/forms.html#controlled-components