Ashan Glenn
Ashan Glenn

Reputation: 27

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;

Upvotes: 1

Views: 254

Answers (4)

Joshua Blevins
Joshua Blevins

Reputation: 71

The beauty of controlled components are that you can control them outside of the DOM. All you simply need to do is set the value state variable to null.

const [myValue, setMyValue] = React.useState(null)

const clearValue = () => {
  setMyValue(null)
}

const handleOnChange = (event) => {
  setMyValue(event.target.value)
}

return <>
  <FormInput
    onChange={handleOnChange}
    value={myValue}
  />
  <Button onClick={clearValue}>Clear</Button>
</>

Since the clear button calls clearValue on click and the clearValue sets myValue to null on click, this should clear the value of your input. Controlled components are driven by a variable, which is updated by what the user types. Uncontrolled components are only driven by what the user types.

To use a controlled component you are required to pass your state variable back to the component though.

Upvotes: 0

codemonkey
codemonkey

Reputation: 7905

You can also use useRef() to control those input elements, which includes clearing them. Declare them for each input like so:

const input1 = React.useRef();
const input2 = React.useRef();

Then use the ref prop of the FormInput:

<FormInput
  ref={input1}
  type="password"
  required
  onChange={handlePasswordChange}
  id="password"
/>

And then you can clear them in your handleSubmit function like so:

input1.current.value = ""

Upvotes: 0

prasanth
prasanth

Reputation: 22490

Its a uncontrolled component. That means single way approach you pass the value from input. But not possible to change the input via Dom.

So better use controlled component value={email}. So this will reset the value via state.

And i have post solution for this uncontrolled component via key updated method.

Example Codesanbox

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

const keyGen = () => 'key'+Math.round(Math.random()*10000000000000);
const SignIn = () => {
  const [key, setKey] = useState(keyGen());
  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("");
    setKey(keyGen())
  };
  return (
    <Container>
      <FormWrap>
        <Icon to="/">Sushi Finder</Icon>
        <FormContent key={key}>
          <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;

Upvotes: 0

Drew Reese
Drew Reese

Reputation: 202608

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"
    />
    

Upvotes: 1

Related Questions