[TIL] input 태그 img tag 눌러서 삭제 오류 해결

이현동·2023년 3월 13일
0

TIL

목록 보기
37/59

input 태그 img tag 눌러서 삭제 오류 해결

아래와 같이 코드를 작성했을 때, input의 value가 삭제는 되었지만 다음과 같은 오류가 발생했다.

...
const Signin = () => {
  const [value, setValue] = useState({ email: "", password: "" });

  const handleInput = (e) => {
    setValue({ ...value, [e.target.name]: e.target.value });
  };
...
  const cancelInput = (e) => {
    setValue({ [e.target.name]: "" });
  };

  return (
		...
        <SignForm id="signin" action="" onSubmit={handleSubmit}>
          <SignText>아이디</SignText>
          <InputWrapper>
            <SignInput
              name="email"
              value={value.email}
              onChange={handleInput}
              placeholder="이메일 주소"
            />
            <img onClick={cancelInput} src={cancel} alt="cancel" name="email" />
          </InputWrapper>
          <SignText>비밀번호</SignText>
          <InputWrapper>
            <SignInput
              name="password"
              value={value.password}
              onChange={handleInput}
              type="password"
              placeholder="영문, 숫자, 특수문자 조합 8자리 이상"
            />
            <img
              onClick={cancelInput}
              src={cancel}
              alt="cancel"
              name="password"
            />
        <SignForm/>
			...
  );
};
...

Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.

input의 value가 잘 삭제가 되었지만, 왜 인지 value가 undefined이라고 오류가 발생하는 것 같다. 그래서 input value|| 연산자를 넣어서 undefined일 때 공백을 지정해주었더니 오류를 막을 수 있었다.

...
<SignInput
  name="email"
  value={value.email}
  onChange={handleInput}
  placeholder="이메일 주소"
            />
...
<SignInput
  name="password"
  value={value.password}
  onChange={handleInput}
  type="password"
  placeholder="영문, 숫자, 특수문자 조합 8자리 이상"
/>
...
profile
https://hdlee.dev

0개의 댓글