How to clear the controlled inputs in ReactJS?

this is a sign-in page I created using React & styled components. I was trying to clear the input field values “onSubmit” but for some issue it does not work. Does anyone knows how should I clear the inputs with the button click ? Thank you!

import React, { useState } from "react";
import {
  Container,
  Form,
  FormButton,
  FormContent,
  FormH1,
  FormInput,
  FormLabel,
  FormWrap,
  Icon,
  Text,
} from "./SigninElements";

const SignIn = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const handleEmailChange = (e) => {
    setEmail(e.target.value);
  };
  const handlePasswordChange = (e) => {
    setPassword(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(email, password);
    setEmail("");
    setPassword("");
  };
  return (
    <Container>
      <FormWrap>
        <Icon to="/">Sushi Finder</Icon>
        <FormContent>
          <Form action="POST" onSubmit={handleSubmit}>
            <FormH1>Sign in to your account</FormH1>
            <FormLabel htmlFor="for">Email</FormLabel>
            <FormInput type="email" required onChange={handleEmailChange} />
            <FormLabel htmlFor="for">Password</FormLabel>
            <FormInput
              type="password"
              required
              onChange={handlePasswordChange}
            />
            <FormButton type="submit">Continue</FormButton>
            <Text>Forgot Password</Text>
          </Form>
        </FormContent>
      </FormWrap>
    </Container>
  );
};

export default SignIn;

Answer

What you have are not controlled inputs, as Jayce444 points out. If you want to clear the inputs then you can do 1 of 2 things:

  1. Actually make your inputs controlled by setting the value prop accordingly. Then the state updates in the submit handler will clear the state and be reflected in the inputs’ values.

    <FormInput
      type="email"
      required
      onChange={handleEmailChange}
      value={email}
    />
    ...
    <FormInput
      type="password"
      required
      onChange={handlePasswordChange}
      value={password}
    />
    
  2. Leave them uncontrolled and clear the inputs via the onSubmit event in the handler. Provide an id for each input to access in the submit handler and reset their values.

    const handleSubmit = (e) => {
      e.preventDefault();
    
      console.log(email, password);
      setEmail("");
      setPassword("");
    
      e.target.email.value = "";
      e.target.password.value = "";
    };
    
    ...
    
    <FormInput
      type="email"
      required
      onChange={handleEmailChange}
      id="email"
    />
    ...
    <FormInput
      type="password"
      required
      onChange={handlePasswordChange}
      id="password"
    />
    

Leave a Reply

Your email address will not be published. Required fields are marked *