순수 자바스크립트로 코딩할 땐 이런 코드를 작성했다.
document.getElementById("nickname").value = "";
하지만 페이지 전체를 탐색하는 것은 비효율적이기 때문에 이 방식을 쓰지 않으려고 부단히 노력했다.
value={isSubmit ? "" : undefined}
를 작성한다. isSubmit = True
에 ""가 되면 초기화가 되고, isSubmit = False
가 되면 undefined
가 되면서 textarea에 값을 입력할 수 있다.
주의🚨 value = ""
로 하면 초기화는 되지만 값을 입력할 수 없는 readonly 상태가 된다.
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);
}}
/>
);
};
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
가 되어서 나타나는 건데, 이렇게 하지 않으면 초기화할 방법이 없어서 일단은 경고를 해결하지 않을 것이다.