Skip to content

Commit

Permalink
fix(forwardRef): fix error boundary not forwarding the ref
Browse files Browse the repository at this point in the history
  • Loading branch information
Rendez committed Mar 24, 2020
1 parent e43da14 commit 568cd57
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/IntersectionObserver.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,20 +183,32 @@ class IntersectionObserver extends React.Component {
}
}

class GuardedIntersectionObserver extends React.Component {
class ErrorBoundary extends React.Component {
static displayName = 'ErrorBoundary(IntersectionObserver)';

static propTypes = {
forwardedRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
};

componentDidCatch(error, info) {
if (Config.errorReporter) {
Config.errorReporter(error, info);
}
}

render() {
return <IntersectionObserver {...this.props} />;
const { forwardedRef, ...props } = this.props;

return <IntersectionObserver ref={forwardedRef} {...props} />;
}
}

const GuardedIntersectionObserver = React.forwardRef((props, ref) => (
<ErrorBoundary forwardedRef={ref} {...props} />
));

GuardedIntersectionObserver.displayName = 'IntersectionObserver';

export {
GuardedIntersectionObserver as default,
IntersectionObserver,
Expand Down
17 changes: 17 additions & 0 deletions src/__tests__/IntersectionObserver.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,23 @@ test('reports errors by re-throwing trying observer children without a DOM node'
Config.errorReporter = originalErrorReporter;
});

test('error boundary forwards ref', () => {
let observer;
renderer.create(
<GuardedIntersectionObserver
onChange={noop}
ref={(instance) => {
observer = instance;
}}
>
<div />
</GuardedIntersectionObserver>,
{ createNodeMock }
);

expect(observer instanceof IntersectionObserver).toBe(true);
});

test('should not observe children that equal null or undefined', () => {
const sizeBeforeObserving = observerElementsMap.size;
renderer.create(
Expand Down

0 comments on commit 568cd57

Please sign in to comment.