0

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:

const SignIn: React.FC = () => {
    const [info, setInfo] = useState({
        email: "",
        password: "",
    })

    const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault()

        setInfo({
            email: "",
            password: "",
        })
    }
    const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const { value, name } = event.target
        setInfo({ ...info, [name]: value })
    }
    return (
        <div className="sign-in">
            <h2>I already have an account</h2>
            <span>Sign in with your email and password</span>

            <form onSubmit={handleSubmit}>
                <FormInput
                    label="Email"
                    name="email"
                    type="email"
                    value={info.email}
                    handleChange={handleChange}
                    required
                />
                <FormInput
                    label="Password"
                    name="password"
                    type="password"
                    value={info.password}
                    handleChange={handleChange}
                    required
                />
            </form>
        </div>
    )
}

And this is my FormInput component:

const FormInput: React.FC<Props> = ({ handleChange, label, value, ...otherProps }) => {
    return (
        <div className="group">
            <input className="form-input" onChange={handleChange} {...otherProps} />
            {label ? (
                <label className={`${value.length ? "shrink" : ""} form-input-label`}>
                    {label}
                </label>
            ) : null}
        </div>
    )
}

1 Answer 1

1

You missed to pass the value to input in your FormInput component that's why it is not getting cleared.

const FormInput = ({ handleChange, label, value, ...otherProps }) => {
  return (
    <div className="group">
      <input className="form-input" value={value} onChange={handleChange} {...otherProps} />
      {label ? (
        <label className={`${value.length ? "shrink" : ""} form-input-label`}>
          {label}
        </label>
      ) : null}
    </div>
  );
};
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.