Skip to content

Commit 568cd57

Browse files
committed
fix(forwardRef): fix error boundary not forwarding the ref
1 parent e43da14 commit 568cd57

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

src/IntersectionObserver.js

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,20 +183,32 @@ class IntersectionObserver extends React.Component {
183183
}
184184
}
185185

186-
class GuardedIntersectionObserver extends React.Component {
186+
class ErrorBoundary extends React.Component {
187187
static displayName = 'ErrorBoundary(IntersectionObserver)';
188188

189+
static propTypes = {
190+
forwardedRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
191+
};
192+
189193
componentDidCatch(error, info) {
190194
if (Config.errorReporter) {
191195
Config.errorReporter(error, info);
192196
}
193197
}
194198

195199
render() {
196-
return <IntersectionObserver {...this.props} />;
200+
const { forwardedRef, ...props } = this.props;
201+
202+
return <IntersectionObserver ref={forwardedRef} {...props} />;
197203
}
198204
}
199205

206+
const GuardedIntersectionObserver = React.forwardRef((props, ref) => (
207+
<ErrorBoundary forwardedRef={ref} {...props} />
208+
));
209+
210+
GuardedIntersectionObserver.displayName = 'IntersectionObserver';
211+
200212
export {
201213
GuardedIntersectionObserver as default,
202214
IntersectionObserver,

src/__tests__/IntersectionObserver.spec.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,23 @@ test('reports errors by re-throwing trying observer children without a DOM node'
141141
Config.errorReporter = originalErrorReporter;
142142
});
143143

144+
test('error boundary forwards ref', () => {
145+
let observer;
146+
renderer.create(
147+
<GuardedIntersectionObserver
148+
onChange={noop}
149+
ref={(instance) => {
150+
observer = instance;
151+
}}
152+
>
153+
<div />
154+
</GuardedIntersectionObserver>,
155+
{ createNodeMock }
156+
);
157+
158+
expect(observer instanceof IntersectionObserver).toBe(true);
159+
});
160+
144161
test('should not observe children that equal null or undefined', () => {
145162
const sizeBeforeObserving = observerElementsMap.size;
146163
renderer.create(

0 commit comments

Comments
 (0)