📝 ErrorNote
[React ] input 컴포넌트 분리하기 중 에러 / Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? Check the render method of `ForwardRef(_c)`.
minhe2810
2024. 6. 25. 09:49
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? Check the render method of `ForwardRef(_c)`.
번역하면,
경고: 함수 구성요소에는 참조를 제공할 수 없습니다. 이 참조에 액세스하려는 시도는 실패합니다. React.forwardRef()를 사용하려고 하셨나요? `ForwardRef(_c)`의 렌더링 방법을 확인하세요.
구조를 보면 다음과 같다.
<div className="form-group row">
<div className="col-sm-9 mb-3 mb-sm-0">
<EmailInput
ref={emailRef}
value={formData.email}
onChange={handleInputChange}
/>
</div>
</div>
회원가입 폼(JoinForm.jsx)에서 input이 많아 불필요한 렌더링이 계속해서 발생하는 것이 비효율적이라고 생각했다.
그래서 각 input을 컴포넌트화해서 분리하려고 하는데 그 과정에서 에러가 발생했다.
import React, { forwardRef } from "react";
import { InputField } from "../common/input/InputField";
const EmailInput = forwardRef(({ value, onChange, onBlur }, ref) => {
const handleChange = (event) => {
console.log("email input Change value");
onChange(event);
};
return (
<InputField
data-name="이메일"
data-check={true}
name="email"
className="form-control form-control-user"
value={value}
onBlur={onBlur}
onChange={handleChange}
placeholder="이메일 주소"
ref={ref}
/>
);
});
export default EmailInput;
컴포넌트들끼리 ref를 props를 주고받기 위해서는 forwardRef 를 사용해야하기 때문에
함수형 컴포넌트 선언 시 forwardRef를 선언했는데.. 왜 계속 에러가 발생하지?
알고 보니
InputField 컴포넌트에서 ref 를 선언해주지 않았기 때문에 email input요소에 접근이 어려웠던 것이다.
import React, { forwardRef } from "react";
export const InputField = forwardRef( // 수정
(
{
name,
type = "text",
className,
maxLength,
value,
onChange,
onBlur,
placeholder,
...rest
},
ref // 추가
) => {
return (
<>
<input
ref={ref} // 추가
name={name}
type={type}
className="form-control form-control-user"
maxLength={maxLength}
value={value}
onChange={onChange}
onBlur={onBlur}
placeholder={placeholder}
{...rest}
/>
</>
);
}
);
이렇게 ref를 모든 컴포넌트들에 작성을 하여 ref 값을 주고받을 수 있도록 설정하자
이렇게 콘솔에 드디어 ref 값이 출력되고 값을 불러올 수 있게 되었다.
참고로 아직 이 코드는 값을 부모 컴포넌트에서 관리하기 때문에 렌더링 최적화가 완전히 이루어진 것은 아니다.
input을 나눠놓고 값을 각각 관리하고자 한다.