기타 보관함/개발자정보

React 커스텀 컴포넌트 포커스 이동

오아름 샘 2025. 5. 22. 15:02
반응형
  • input2Ref는 단순한 <input />이 아니라,
  • AutoComplete: React.ForwardRefExoticComponent<...> 즉, ref forwarding이 가능한 커스텀 컴포넌트입니다.
  • 그런데 input2Ref.current?.focus()를 호출해도 실제 DOM 포커싱이 이동하지 않음.

이는 커스텀 AutoComplete 컴포넌트가 ref를 실제 DOM input에 제대로 forward하지 않았기 때문입니다.


✅ 해결 방법 요약

✅ 1. AutoComplete 컴포넌트가 ref를 내부 input에 전달하도록 구현되어야 합니다

커스텀 컴포넌트에서 ref를 사용하려면, React.forwardRef로 감싸고 ref를 내부 input에 전달해야 합니다:

// AutoComplete.tsx
import React, { forwardRef } from 'react';

export const AutoComplete = forwardRef<HTMLInputElement, AutoCompleteProps>((props, ref) => {
  return (
    <input
      type="text"
      ref={ref} // <-- 중요!
      {...props}
    />
  );
});

이렇게 하면 부모에서 ref.current.focus()를 호출할 때 실제 <input>에 포커스가 이동합니다.


✅ 2. 만약 외부 라이브러리라면

만약 AutoComplete가 외부 라이브러리(예: MUI, Ant Design, react-select 등)라면:

  • ref가 input이 아닌 다른 컴포넌트(ex. div)에 걸려 있을 수 있습니다.
  • 또는 내부적으로 inputRef 등의 별도 prop이 존재할 수 있습니다.

예를 들어 MUI Autocomplete의 경우:

<Autocomplete
  inputValue={inputValue}
  onInputChange={handleInputChange}
  renderInput={(params) => (
    <TextField
      {...params}
      inputRef={input2Ref} // 이렇게 해야 포커싱 가능
      label="조건 2"
/>
  )}
/>

✅ 진단 방법

  1. console.log(input2Ref.current) 를 찍어보세요.
    • null → 아직 렌더 안 됐거나 ref 전달 안 됨
    • HTMLInputElement 아님 → 내부 DOM이 아님
  2. 내부에서 <input ref={ref} /> 로 전달했는지 확인

✅ 해결 요약

상황 해결 방법

직접 만든 AutoComplete React.forwardRef 사용해 내부 <input>에 ref 전달
외부 라이브러리 사용 문서 확인 후 inputRef 또는 getInputElement() 등 활용
포커싱 안 됨 console.log(ref.current) 확인하여 진짜 input인지 확인

 

반응형