Skip to content

Commit 609e1a5

Browse files
joaovieiraRendez
authored andcommitted
fix(ref): Handle ref objects in children prop.
1 parent e35286b commit 609e1a5

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

src/IntersectionObserver.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,9 +104,18 @@ export default class IntersectionObserver extends React.Component {
104104
};
105105

106106
handleNode = target => {
107-
if (typeof this.props.children.ref === 'function') {
108-
this.props.children.ref(target);
107+
/**
108+
* Forward hijacked ref to user.
109+
*/
110+
const nodeRef = this.props.children.ref;
111+
if (nodeRef) {
112+
if (typeof nodeRef === 'function') {
113+
nodeRef(target);
114+
} else if (typeof nodeRef === 'object') {
115+
nodeRef.current = target;
116+
}
109117
}
118+
110119
/**
111120
* This is a bit ugly: would like to use getSnapshotBeforeUpdate(), but we do not want to depend on
112121
* react-lifecycles-compat to support React versions prior to 16.3 as this extra boolean gets the job done.

src/__tests__/IntersectionObserver.spec.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,19 @@ test('should call ref callback of children', () => {
7272
expect(spy).toHaveBeenCalledWith(target);
7373
});
7474

75+
test('should handle children ref of type RefObject', () => {
76+
const ref = React.createRef();
77+
const component = (
78+
<IntersectionObserver onChange={noop}>
79+
<span ref={ref} />
80+
</IntersectionObserver>
81+
);
82+
83+
renderer.create(component, { createNodeMock: () => target });
84+
85+
expect(ref.current).toEqual(target);
86+
});
87+
7588
test('options getter returns propTypes `root`, `rootMargin` and `threshold`', () => {
7689
const options = { root: { nodeType: 1 }, rootMargin: '50% 0%', threshold: [0, 1] };
7790
const component = (

0 commit comments

Comments
 (0)