How to clear textarea(input) in react

hotbreakb·2022년 6월 11일
0
post-thumbnail

➡️ Github로 이동

순수 자바스크립트로 코딩할 땐 이런 코드를 작성했다.

document.getElementById("nickname").value = "";

하지만 페이지 전체를 탐색하는 것은 비효율적이기 때문에 이 방식을 쓰지 않으려고 부단히 노력했다.

방법

value={isSubmit ? "" : undefined}를 작성한다. isSubmit = True에 ""가 되면 초기화가 되고, isSubmit = False가 되면 undefined가 되면서 textarea에 값을 입력할 수 있다.

주의🚨 value = ""로 하면 초기화는 되지만 값을 입력할 수 없는 readonly 상태가 된다.

textarea

export const Textarea = ({
  ... }: TextareaProps) => {
  const textareaRef = useRef(null);
  return (
    <StyledTextarea
      ref={textareaRef}
      disabled={disabled}
      width={width}
      height={height}
      placeholder={placeholder}
      value={isSubmit ? "" : undefined}
      onMouseOut={() => {
        handleDescription((textareaRef.current as any).value);
      }}
    />
  );
};

input

textarea와 같은 방식으로 value={isSubmit ? "" : undefined}를 추가한다.

export const Input = forwardRef<HTMLInputElement, InputProps>(
  (
    { ... }: InputProps, ref
  ) => (
    <StyledInput
      ref={ref}
      disabled={disabled}
      width={width}
      height={height}
      placeholder={placeholder}
      value={isSubmit ? "" : undefined}
    />
  )
);
Warning: A component is changing an uncontrolled input of type text to be controlled.

위처럼 작성하면 input에서 경고가 발생한다. value = undefined가 되어서 나타나는 건데, 이렇게 하지 않으면 초기화할 방법이 없어서 일단은 경고를 해결하지 않을 것이다.

profile
글쟁이 프론트 개발자, 헬렌입니다.

0개의 댓글