Skip to content
Advertisement

My input didn’t update value when I update state

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>
    )
}

Advertisement

Answer

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>
  );
};
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement