For debugging issue, currently I’ve got to implement some code to wrap all the (named & default) exported React components (including React components inside namespace) with ErrorBoundary HOC to find out where the issue arose from.
React components that might look something like this should be wrapped:
- ex.1
export const BaseButton01 = React.memo(
React.forwardRef<Types.RefElement, Types.Props>((props, ref) => {
return <Styles.BaseButton01 ref={ref} {...props} />;
})
);
BaseButton01.displayName = "BaseButton01";
- ex.2
export const SomeJsx = <button>Some Button</button>
Maybe ErrorBoundary class component and HOC might look something like:
import React, { Component } from "react";
import * as Types from "./types";
export { Types as ErrorBoundary02Types };
export class ErrorBoundary02 extends Component<Types.Props, Types.State> {
state: Types.State = {
hasError: false,
error: null,
errorInfo: null
};
static getDerivedStateFromError(error: Error): Types.State {
return { hasError: true, error, errorInfo: null };
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
console.error(
`Error caught in ${this.props.componentName}:`,
error,
errorInfo
);
this.setState({ errorInfo });
}
render() {
if (this.state.hasError) {
return (
<div>
<h2>Something went wrong in {this.props.componentName}.</h2>
<details style={{ whiteSpace: "pre-wrap" }}>
{this.state.error && this.state.error.toString()}
<br />
{this.state.errorInfo?.componentStack}
</details>
</div>
);
}
return this.props.children;
}
}
export function withErrorBoundary<T extends object>(
WrappedComponent: React.ComponentType<T>
) {
return class extends Component<T> {
render() {
return (
<ErrorBoundary>
<WrappedComponent {...this.props as T} />
</ErrorBoundary>
);
}
};
}
Please help!! I’ve been working with this for a week already!!