Skip to content

Commit

Permalink
feat(react): Support render props in ErrorBoundary (#3793)
Browse files Browse the repository at this point in the history
Extend the ErrorBoundary component to allow it to support render props
children. This means that patterns like the following are viable:

```jsx
<Sentry.ErrorBoundary>
  {() => (
    <Suspense fallback={<div>Loading...</div>}>
      <Other />
    </Suspense>
  )}
</Sentry.ErrorBoundary>
```

Fixes #3052
  • Loading branch information
AbhiPrasad authored Jul 12, 2021
1 parent 8063fbb commit 3095f4b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
7 changes: 5 additions & 2 deletions packages/react/src/errorboundary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundarySta
};

public render(): React.ReactNode {
const { fallback } = this.props;
const { fallback, children } = this.props;
const { error, componentStack, eventId } = this.state;

if (error) {
Expand All @@ -171,7 +171,10 @@ class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundarySta
return null;
}

return this.props.children;
if (typeof children === 'function') {
return children();
}
return children;
}
}

Expand Down
8 changes: 8 additions & 0 deletions packages/react/test/errorboundary.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,14 @@ describe('ErrorBoundary', () => {
expect(container.innerHTML).toBe('<h1>children</h1>');
});

it('supports rendering children as a function', () => {
const { container } = render(
<ErrorBoundary fallback={<h1>Error Component</h1>}>{() => <h1>children</h1>}</ErrorBoundary>,
);

expect(container.innerHTML).toBe('<h1>children</h1>');
});

describe('fallback', () => {
it('renders a fallback component', async () => {
const { container } = render(
Expand Down

0 comments on commit 3095f4b

Please sign in to comment.