I have an error boundary on top of my app. It works, and I can pass it a custom component as a fallback. However, Typescript claims that:
Property 'fallback' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' (errorboundary.js)
and that
No overload matches this call. (index.tsx)
import { Component } from "react";
export class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
render() {
if (this.state.error) {
return this.props.fallback;
}
return this.props.children;
}
}
How to fix this?
Please note I'm not using the react-error-boundary library. The native error boundary class should do the work.
EDIT: complete working code:
interface Props {
fallback: React.ReactNode;
}
export class ErrorBoundary extends Component<Props> {
state = { error: null };
static defaultProps: Props = {
fallback: [],
};
static getDerivedStateFromError(error) {
return { error };
}
render() {
if (this.state.error) {
return this.props.fallback;
}
return this.props.children;
}
}
You should extend Component
passing the type definition of your props, like this:
interface ErrorBoundaryProps {
fallback: JSX.Element; // if fallback is a JSX.Element
}
interface ErrorBoundaryState {
error: boolean | null;
}
export class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> { ... }