Skip to content

Commit

Permalink
Merge pull request #278 from Andarist/support-forward-ref
Browse files Browse the repository at this point in the history
Add support for React.forwardRef and React.createRef
  • Loading branch information
trotzig authored Nov 20, 2018
2 parents 99237f7 + 3960e0d commit 5a72874
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 6 deletions.
29 changes: 26 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,9 +278,32 @@ composite component (e.g. `<MyComponent />`).

Waypoint needs a DOM node to compute its boundaries. When you pass a DOM
component to Waypoint, it handles getting a reference to the DOM node through
the `ref` prop automatically. If you pass a composite component, you need to
make use of the `innerRef` prop passed by Waypoint to your component. Simply
pass it through as the `ref` of a DOM component and you're all set. Like in
the `ref` prop automatically.

If you pass a composite component, you can wrap it with `React.forwardRef` (requires `react@^16.3.0`)
and have the `ref` prop being handled automatically for you, like this:

```jsx
class Block extends React.Component {
render() {
return <div ref={this.props.innerRef}>Hello</div>
}
}

const BlockWithRef = React.forwardRef((props, ref) => {
return <Block innerRef={ref} {...props} />
})

const App = () => (
<Waypoint>
<BlockWithRef />
</Waypoint>
)
```

If you can't do that because you are using older version of React then
you need to make use of the `innerRef` prop passed by Waypoint to your component.
Simply pass it through as the `ref` of a DOM component and you're all set. Like in
this example:

```jsx
Expand Down
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 5a72874

Please sign in to comment.