개발/버그일지

input에서 한글자 입력시 focus 잃는 현상

pizzaYami 2023. 10. 10.

 

프로젝트를 진행하다가 다른 팀원분이 리팩토링을 해주셨는데 그 후에 input에 한 글자씩 입력을 해도 focus가 없어지는 현상이 생겼다.

(유지보수는 나의 것...)

 

블로그 를 찾아보니 글자를 입력할 때마다 rerender가 되기 때문에 이러한 현상이 생겼다.

코드를 보자.

 

문제 코드

const CommentInput = ({
  userInfo,
  postData,
  setCommentFlip,
  inputToggleBind,
  isCommentBind,
}: commentInputProps) => {
  const { state: inputToggle, Setter: setInputToggle } = inputToggleBind;
  const { state: isComment, Setter: setIsComment } = isCommentBind;
  const [commentInputText, setCommentInputText] = useState<string>('');

  ...안봐도 되는 코드들
  
  // 문제의 컴포넌트
  const CommentContent = (): JSX.Element => {
    return (
      <CommentInputS inputToggle={inputToggle} onClick={handleFormClickFalse}>
        <InputS inputToggle={inputToggle}>
          <input
            placeholder={placeholderText()}
            value={commentInputText}
            onChange={handleInputChange}
            type='text'
            maxLength={400}
          />
          <button onClick={inputBtnHandler}>
            {
              <img
                src={`${process.env.PUBLIC_URL}/commentInputButton${isTyping}.svg`}
                alt='sendIcon'
              />
            }
          </button>
        </InputS>
      </CommentInputS>
    );
  };
  return inputToggle ? (
    <CommentContent />
  ) : (
    <CommentFormBGS inputToggle={inputToggle} onClick={handleFormClickTrue}>
      <CommentContent />
    </CommentFormBGS>
  );
};

};

 

CommentInput 컴포넌트 내부에서 CommentContent 컴포넌트를 반환하는 방식을 사용하고 있기 때문에 이 부분에서 CommentInput 함수 컴포넌트를 재호출 하면서 계속 새로운 컴포넌트를 만들고 있기 때문에 재렌더링 될 때마다 포커스가 사라지고 있던 것이었다.

 

리팩토링을 진행하면서 props를 줄이고 싶으셔서 컴포넌트내부에 새로운 컴포넌트를 만들면서 생긴 문제였다.

 

 

해결된 코드


  const CommentInputContent = (
    <CommentInputContainerS inputToggle={inputToggle} onClick={handleFormClickFalse}>
      <CommentInputS inputToggle={inputToggle}>
        <input
          placeholder={placeholderText()}
          value={commentInputText}
          onChange={handleInputChange}
          type='text'
          maxLength={400}
        />
        <button onClick={inputBtnHandler}>
          {
            <img
              src={`${process.env.PUBLIC_URL}/commentInputButton${isTyping}.svg`}
              alt='sendIcon'
            />
          }
        </button>
      </CommentInputS>
    </CommentInputContainerS>
  );

  return inputToggle ? (
    CommentInputContent
  ) : (
    <CommentInputBGS inputToggle={inputToggle} onClick={handleFormClickTrue}>
      {CommentInputContent}
    </CommentInputBGS>
  );
};

export { CommentInput };

 

컴포넌트명을 변경하였고 내부 컴포넌트를 변수로 변경하여 적용하였다.

 

내부에 컴포넌트를 외부로 빼고 싶긴 한데 props가 너무 많아져서 적용하지는 않았다.

댓글