I made two components, one is sign in component and one is form input.
I pass props to form input to render some input form.
And I also had a state to save the value of this inputs (two way binding).
Rendering is fine till now.
The problem when I submit form and set state to initial, i saw the state change in console log but my inputs didn’t display that, they still had displayed the last values that I submited.
Thanks for your help
This is my SignIn component:
JavaScript
x
45
45
1
const SignIn: React.FC = () => {
2
const [info, setInfo] = useState({
3
email: "",
4
password: "",
5
})
6
7
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
8
event.preventDefault()
9
10
setInfo({
11
email: "",
12
password: "",
13
})
14
}
15
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
16
const { value, name } = event.target
17
setInfo({ info, [name]: value })
18
}
19
return (
20
<div className="sign-in">
21
<h2>I already have an account</h2>
22
<span>Sign in with your email and password</span>
23
24
<form onSubmit={handleSubmit}>
25
<FormInput
26
label="Email"
27
name="email"
28
type="email"
29
value={info.email}
30
handleChange={handleChange}
31
required
32
/>
33
<FormInput
34
label="Password"
35
name="password"
36
type="password"
37
value={info.password}
38
handleChange={handleChange}
39
required
40
/>
41
</form>
42
</div>
43
)
44
}
45
And this is my FormInput component:
JavaScript
1
13
13
1
const FormInput: React.FC<Props> = ({ handleChange, label, value, otherProps }) => {
2
return (
3
<div className="group">
4
<input className="form-input" onChange={handleChange} {otherProps} />
5
{label ? (
6
<label className={`${value.length ? "shrink" : ""} form-input-label`}>
7
{label}
8
</label>
9
) : null}
10
</div>
11
)
12
}
13
Advertisement
Answer
You missed to pass the value
to input in your FormInput
component that’s why it is not getting cleared.
JavaScript
1
13
13
1
const FormInput = ({ handleChange, label, value, otherProps }) => {
2
return (
3
<div className="group">
4
<input className="form-input" value={value} onChange={handleChange} {otherProps} />
5
{label ? (
6
<label className={`${value.length ? "shrink" : ""} form-input-label`}>
7
{label}
8
</label>
9
) : null}
10
</div>
11
);
12
};
13