Skip to content

Commit

Permalink
Add support for React.forwardRef and React.createRef
Browse files Browse the repository at this point in the history
Components wrapped with `React.forwardRef` will now correctly have their refs passed to `react-waypoint` as they don't recognize custom `innerRef` prop, but should know what to do with received `ref` (that is - pass it to underlaying DOM element).

Also the support for `React.createRef` has been added - which is a new React API, an alternative to callback refs. It returns an object with shape of `{ current: null }`, so the ref can and should be set on the `current` property (it's done by React internally when passingit as ref prop to an element).
  • Loading branch information
Andarist committed Nov 19, 2018
1 parent 284a937 commit a1ff00d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
],
"dependencies": {
"consolidated-events": "^1.1.0 || ^2.0.0",
"prop-types": "^15.0.0"
"prop-types": "^15.0.0",
"react-is": "^16.6.3"
}
}
9 changes: 7 additions & 2 deletions src/waypoint.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { addEventListener } from 'consolidated-events';
import PropTypes from 'prop-types';
import React from 'react';
import { isForwardRef } from 'react-is';

import computeOffsetPixels from './computeOffsetPixels';
import constants from './constants';
Expand Down Expand Up @@ -295,11 +296,15 @@ export default class Waypoint extends BaseClass {
return <span ref={this.refElement} style={{ fontSize: 0 }} />;
}

if (isDOMElement(children)) {
if (isDOMElement(children) || isForwardRef(children.type)) {
const ref = (node) => {
this.refElement(node);
if (children.ref) {
children.ref(node);
if (typeof children.ref === 'function') {
children.ref(node);
} else {
children.ref.current = node;
}
}
};

Expand Down

0 comments on commit a1ff00d

Please sign in to comment.