Property 'ref' does not exist on type 'IntrinsicAttributes'

Viewed 1981

I'm working on a React typescript project. The code works but ts compiler keeps complaining about my ref. Here is the code:

First I have a high order component to handle errors:

export class ErrorBoundary extends React.Component<ErrorBoundaryProps> {
    constructor(props: ErrorBoundaryProps) {
        super(props);
    }

    static getDerivedStateFromError(error: any) {
       // some error handling related code
    }

    public componentDidCatch(error: any) {
        // some error handling related code
    }

    public render() {
       return this.props.children;
    }
}

And a high order component:

export function withErrorBoundary<T = {}>(Component: React.ComponentType<T>): React.ComponentType<T> {
    function Wrapped(props: T) {
        return (
            <ErrorBoundary>
                <Component {...props} />
            </ErrorBoundary>
        );
    }
    return Wrapped;
}

This has worked well like this: const NewComponent = withErrorBoundary(MyComponent)

But now I'm building a new component that has the need of React.forwardRef:

interface ILabelProps {
  value: string;
  mark: boolean;
  // other props with basic types
}
export const Label = React.forwardRef(
    (props: ILabelProps, ref) => {
    React.useImperativeHandle(ref, () => ({
        // some custom logic
    }), []);

    return (
        <>{...my UI}</>
    );
});

export MyLabel = withErrorBoundary(Label);

However when I use it like this it errors out about the ref:

Property 'ref' does not exist on type 'IntrinsicAttributes & ILabelProps'

const App = () => {
   const labelRef = React.useRef();
   return <MyLabel {...props} ref={labelRef} />
}

However if I just use Label without the errorBoundary HOC, it stops complaining:

const App = () => {
   const labelRef = React.useRef();
   return <Label {...props} ref={labelRef} />
}

I think the issue might be related the use of React.forwardRef because this is the first time I used it and I've never had this kind of issue before. Any one knows how to fix this?

Thanks!

1 Answers

I don't see any error when replicate your code.

But it does have 1 error at runtime:

Warning: Function components cannot be given refs. 
Attempts to access this ref will fail. 
Did you mean to use React.forwardRef()?

Basically, your Component MyLabel = withErrorBoundary(Label) is the new Component returned from withErrorBoundaray hence it's lost the forwardRef provided by Label. To fix that you just need to pass labelRef to Label Component like below:

  const MyLabel2 = withErrorBoundary(() => <Label {...props} ref={labelRef} />);

Codesandbox here.

Related