React
ref 오류 : Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
kangju2000
2022. 7. 6. 17:00
import React from 'react';
import PropTypes from 'prop-types';
import * as Style from 'components/Input/Input.styles';
export default function Input ({ status, icon, ...props }) {
return (
<Style.InputContainer>
<Style.Input ref={ref} {...props} />
{icon && <Style.Icon>{icon}</Style.Icon>}
</Style.InputContainer>
);
};
Input.propTypes = {
status: PropTypes.oneOf(['default', 'error']),
icon: PropTypes.element,
};
Input.defaultProps = {
status: 'default',
};
Input 컴포넌트를 만들고 useRef를 사용해서 접근하려고 했지만 이런 오류가 발생했다.
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
구글링을 해보니 부모 컴포넌트에서 자식 컴포넌트의 DOM 요소를 접근할 때는 forwardRef를 사용하여 접근해야 한다고 한다.
해결 방법
import React, { forwardRef } from 'react';
import PropTypes from 'prop-types';
import * as Style from 'components/Input/Input.styles';
const Input = forwardRef(({ status, icon, ...props }, ref) => {
return (
<Style.InputContainer>
<Style.Input ref={ref} {...props} />
{icon && <Style.Icon>{icon}</Style.Icon>}
</Style.InputContainer>
);
});
Input.propTypes = {
status: PropTypes.oneOf(['default', 'error']),
icon: PropTypes.element,
};
Input.defaultProps = {
status: 'default',
};
Input.displayName = 'Input';
export default Input;
참고
https://sambalim.tistory.com/151
React Ref 이해하기
일반적으로 React에서는 부모 컴포넌트와 자식 컴포넌트가 상호작용할 수 있는 수단이 props 밖에 없습니다. 자식을 수정하려면 새로운 props 를 전달하여 자식을 다시 렌더링해야합니다. 하지만 Rea
sambalim.tistory.com