Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(react): Passes the fallback function through React's createElement function #10623

Merged
merged 6 commits into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/react/src/errorboundary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundarySta
if (state.error) {
let element: React.ReactElement | undefined = undefined;
if (typeof fallback === 'function') {
element = fallback({
element = React.createElement(fallback, {
error: state.error,
componentStack: state.componentStack,
resetError: this.resetErrorBoundary,
Expand Down
25 changes: 24 additions & 1 deletion packages/react/test/errorboundary.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@ function Bam(): JSX.Element {
return <Boo title={title} />;
}

function EffectSpyFallback({ error }: { error: Error }): JSX.Element {
const [counter, setCounter] = useState(0);

React.useEffect(() => {
setCounter(c => c + 1);
}, []);

return (
<span>
EffectSpyFallback {counter} - {error.message}
</span>
);
}

interface TestAppProps extends ErrorBoundaryProps {
errorComp?: JSX.Element;
}
Expand Down Expand Up @@ -101,7 +115,7 @@ describe('ErrorBoundary', () => {
it('renders null if not given a valid `fallback` prop function', () => {
const { container } = render(
// @ts-expect-error Passing wrong type on purpose
<ErrorBoundary fallback={() => 'Not a ReactElement'}>
<ErrorBoundary fallback={() => undefined}>
<Bam />
</ErrorBoundary>,
);
Expand All @@ -118,6 +132,15 @@ describe('ErrorBoundary', () => {
expect(container.innerHTML).toBe('<h1>Error Component</h1>');
});

it('renders a fallback that can use react hooks', () => {
const { container } = render(
<ErrorBoundary fallback={EffectSpyFallback}>
<Bam />
</ErrorBoundary>,
);
expect(container.innerHTML).toBe('<span>EffectSpyFallback 1 - boom</span>');
});

it('calls `onMount` when mounted', () => {
const mockOnMount = jest.fn();
render(
Expand Down