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

Handle ref objects in children. #47

Merged
merged 1 commit into from
Oct 23, 2018
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/IntersectionObserver.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,18 @@ export default class IntersectionObserver extends React.Component {
};

handleNode = target => {
if (typeof this.props.children.ref === 'function') {
this.props.children.ref(target);
/**
* Forward hijacked ref to user.
*/
const nodeRef = this.props.children.ref;
if (nodeRef) {
if (typeof nodeRef === 'function') {
nodeRef(target);
} else if (typeof nodeRef === 'object') {
nodeRef.current = target;
}
}

/**
* This is a bit ugly: would like to use getSnapshotBeforeUpdate(), but we do not want to depend on
* react-lifecycles-compat to support React versions prior to 16.3 as this extra boolean gets the job done.
Expand Down
13 changes: 13 additions & 0 deletions src/__tests__/IntersectionObserver.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,19 @@ test('should call ref callback of children', () => {
expect(spy).toHaveBeenCalledWith(target);
});

test('should handle children ref of type RefObject', () => {
const ref = React.createRef();
const component = (
<IntersectionObserver onChange={noop}>
<span ref={ref} />
</IntersectionObserver>
);

renderer.create(component, { createNodeMock: () => target });

expect(ref.current).toEqual(target);
});

test('options getter returns propTypes `root`, `rootMargin` and `threshold`', () => {
const options = { root: { nodeType: 1 }, rootMargin: '50% 0%', threshold: [0, 1] };
const component = (
Expand Down