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!