Skip to content

Commit

Permalink
feat(React16): support for React 16
Browse files Browse the repository at this point in the history
BREAKING CHANGE: <sentinel> tag replaced by a <span> tag.
BREAKING CHANGE: deprecation warning will not longer appear for itemsLength prop.
  • Loading branch information
Luis Merino committed Nov 24, 2017
1 parent 8e5f22f commit 12ba423
Show file tree
Hide file tree
Showing 11 changed files with 792 additions and 728 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
node_modules
npm-debug.log*
yarn-error.log
lib
coverage
docs/static
Expand Down
89 changes: 52 additions & 37 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@
<!-- ### An Infinite Scroller List Component -->

**React Intersection List** builds on top of **[React Intersection Observer](https://github.com/researchgate/react-intersection-observer)**, using a [sentinel](https://en.wikipedia.org/wiki/Sentinel_value) in the DOM to deliver a high-performance and smooth scrolling experience, even on low-end devices.
**React Intersection List** builds on top of
**[React Intersection Observer](https://github.com/researchgate/react-intersection-observer)**, using a
[sentinel](https://en.wikipedia.org/wiki/Sentinel_value) in the DOM to deliver a high-performance and smooth scrolling
experience, even on low-end devices.

## Getting Started

Expand All @@ -43,9 +46,7 @@ export default class MyList extends React.Component {
</ul>
);

itemRenderer = (index, key) => (
<li key={key}>{index}</li>
);
itemRenderer = (index, key) => <li key={key}>{index}</li>;

render() {
return (
Expand All @@ -57,11 +58,15 @@ export default class MyList extends React.Component {
}
```

Note that `<List>` is a `PureComponent` so it can keep itself from re-rendering. It's highly recommended to pass referenced methods for `children` and `itemsRenderer` (in this case instance methods), so that it can successfully shallow compare props.
Note that `<List>` is a `PureComponent` so it can keep itself from re-rendering. It's highly recommended to pass
referenced methods for `children` and `itemsRenderer` (in this case instance methods), so that it can successfully
shallow compare props.

## Why React Intersection List?

The approach to infinite scrolling was commonly done by devs implementing throttled `scroll` event callbacks. This keeps the main thread unnecessarily busy... No more! `IntersectionObservers` invoke callbacks in a **low-priority and asynchronous** way by design.
The approach to infinite scrolling was commonly done by devs implementing throttled `scroll` event callbacks. This keeps
the main thread unnecessarily busy... No more! `IntersectionObservers` invoke callbacks in a **low-priority and
asynchronous** way by design.

> **Agent Smith:** Never send a human to do a machine's job.
Expand All @@ -80,72 +85,82 @@ The implementation follows these steps:
Provided an `itemsRenderer` prop you must attach the `ref` argument to your scrollable DOM element:

```jsx
<div ref={ref}>{items}</div>
<div ref={ref}>{items}</div>;
```

This element specifies `overflow: auto|scroll` and it'll become the `IntersectionObserver root`. If the `overflow` property isn't found, then `window` will be used as the `root` instead.
This element specifies `overflow: auto|scroll` and it'll become the `IntersectionObserver root`. If the `overflow`
property isn't found, then `window` will be used as the `root` instead.

The `<sentinel />` element is by default detached from the list when the current size reaches the available length, unless you're using `awaitMore`. In case your list is in memory and you rely on the list for incremental rendering only, the default detaching behavior suffices. If you're loading items asynchoronously on-demand, make sure to switch `awaitMore` once you reach the total length.
The `sentinel` element is by default detached from the list when the current size reaches the available length, unless
you're using `awaitMore`. In case your list is in memory and you rely on the list for incremental rendering only, the
default detaching behavior suffices. If you're loading items asynchoronously on-demand, make sure to switch `awaitMore`
once you reach the total length.

### FAQ

Q: Why am I receiving too many `onIntersection` callbacks

We extend `React.PureComponent`, so IF the parent component re-renders, and the _props_ passed to your `<List />` don't hold the same reference anymore, the list re-renders and may accidentally be re-attaching the `<sentinel />`.
We extend `React.PureComponent`, so IF the parent component re-renders, and the _props_ passed to your `<List />` don't
hold the same reference anymore, the list re-renders and may accidentally be re-attaching the `sentinel`.

Q: Do I always need to assign the `ref`?

Yes, this callback is used to start up the `IntersectionObserver`.

Q: What's the `threshold` value, and why does it need a _unit_?

The `threshold` value is the amount of space needed before the `<sentinel />` intersects with the root. The prop is transformed into a valid `rootMargin` property for the `IntersectionObserver`, depending on the `axis` you select. As a sidenote, we believe that a percentage unit works best for responsive layouts.
The `threshold` value is the amount of space needed before the `sentinel` intersects with the root. The prop is
transformed into a valid `rootMargin` property for the `IntersectionObserver`, depending on the `axis` you select. As a
sidenote, we believe that a percentage unit works best for responsive layouts.

Q: I am getting a console warning when I first load the list

> The sentinel detected a viewport with a bigger size than the size of its items...
The prop `pageSize` is `10` by default, so make sure you're not falling short on items when you first render the component. The idea of an infinite scrolling list is that items overflow the viewport, so that users have the impression that there're always more items available.
The prop `pageSize` is `10` by default, so make sure you're not falling short on items when you first render the
component. The idea of an infinite scrolling list is that items overflow the viewport, so that users have the impression
that there're always more items available.

Q: Why doesn't the list render my updated list element(s)?

The list renders items based on its props. An update somewhere else in your app (or within your list item) might update your list element(s), but if your list's `currentLength` prop for instance, remains unchanged, the list prevents a re-render. Updating the entire infinite list when one of its items has changed is far from optimal. Instead, update your list items independently using internal state or something like react-redux's connect().
The list renders items based on its props. An update somewhere else in your app (or within your list item) might update
your list element(s), but if your list's `currentLength` prop for instance, remains unchanged, the list prevents a
re-render. Updating the entire infinite list when one of its items has changed is far from optimal. Instead, update your
list items independently using internal state or something like react-redux's connect().

Q: Are you planning to implement a "virtual list mode" like react-virtualized?

Yes, there's already an [open issue](https://github.com/researchgate/react-intersection-list/issues/2) to implement a mode using occlusion culling.

### Options

- **children**: `(index: number, key: number) => React.Element<*>`

- **itemsRenderer**: `(items: Array<React.Element<*>>, ref: HTMLElement) => React.Element<*>`

- **currentLength**: `number` | default: `0` (number of renderable items)
Yes, there's already an [open issue](https://github.com/researchgate/react-intersection-list/issues/2) to implement a
mode using occlusion culling.

- **awaitMore**: `bool` | default: `false` (if true keeps the sentinel from detaching)
### Props

- **onIntersection**: `(size: number, pageSize: number) => void` (invoked when the sentinel comes into view)

- **threshold**: `string` | default: `100px` (specify in absolute `px` or `%` value)

- **axis**: `'x' | 'y'` | default: `y`

- **pageSize**: `number` | default: `10` (number of items to render per page)

- **initialIndex**: `number` | default: `0`
| property | type | default | description |
| ---------------- | ------------------------------------------------------------------ | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `children` | `(index: number, key: number) => React.Element` | `(index, key) => <div key={key}>{index}</div>` | render function as children;<br />gets call once for each item. |
| `itemsRenderer` | `(items: Array(React.Element), ref: HTMLElement) => React.Element` | `(items, ref) => <div ref={ref}>{items}</div>` | render function for the list's<br />root element, often returning a scrollable element. |
| `currentLength` | `number` | `0` | item count to render. |
| `awaitMore` | `boolean` | | if true keeps the sentinel from detaching. |
| `onIntersection` | `(size: number, pageSize: number) => void` | | invoked when the sentinel comes into view. |
| `threshold` | `string` | `100px` | value in absolute `px` or `%`<br />as spacing before the sentinel hits the edge of the list's viewport. |
| `axis` | `string` | `y` | scroll direction: `y` == vertical and `x` == horizontal |
| `pageSize` | `number` | `10` | number of items to render each hit. |
| `initialIndex` | `number` | `0` | start position of iterator of items. |

### Examples

Find multiple examples under: [https://researchgate.github.io/react-intersection-list/](https://researchgate.github.io/react-intersection-list/)

Find multiple examples under:
[https://researchgate.github.io/react-intersection-list/](https://researchgate.github.io/react-intersection-list/)

## Contributing

We'd love your help on creating React Intersection List!

Before you do, please read our [Code of Conduct](.github/CODE_OF_CONDUCT.md) so you know what we expect when you contribute to our projects.
Before you do, please read our [Code of Conduct](.github/CODE_OF_CONDUCT.md) so you know what we expect when you
contribute to our projects.

Our [Contributing Guide](.github/CONTRIBUTING.md) tells you about our development process and what we're looking for, gives you instructions on how to issue bugs and suggest features, and explains how you can build and test your changes.
Our [Contributing Guide](.github/CONTRIBUTING.md) tells you about our development process and what we're looking for,
gives you instructions on how to issue bugs and suggest features, and explains how you can build and test your changes.

**Haven't contributed to an open source project before?** No problem! [Contributing Guide](.github/CONTRIBUTING.md) has you covered as well.
**Haven't contributed to an open source project before?** No problem! [Contributing Guide](.github/CONTRIBUTING.md) has
you covered as well.
70 changes: 29 additions & 41 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,81 +8,69 @@
},
"dependencies": {
"@researchgate/react-intersection-observer": "^0.5.0",
"prop-types": "^15.5.10",
"prop-types": "^15.6.0",
"warning": "^3.0.0"
},
"devDependencies": {
"@researchgate/babel-preset-rg": "^1.0.1",
"@researchgate/eslint-config-rg-react": "^1.0.0",
"@storybook/addon-options": "^3.2.4",
"@storybook/react": "^3.2.8",
"@researchgate/eslint-config-rg-react": "^1.0.1",
"@storybook/addon-options": "^3.2.16",
"@storybook/react": "^3.2.16",
"babel-cli": "^6.24.1",
"babel-core": "^6.26.0",
"babel-eslint": "^8.0.0",
"babel-jest": "^21.0.0",
"babel-eslint": "^8.0.2",
"babel-jest": "^21.2.0",
"conventional-github-releaser": "^2.0.0",
"cross-env": "^5.0.5",
"cross-env": "^5.1.1",
"css-loader": "^0.28.4",
"eslint": "^4.6.1",
"eslint-config-prettier": "^2.4.0",
"eslint-plugin-import": "^2.7.0",
"eslint": "^4.11.0",
"eslint-config-prettier": "^2.8.0",
"eslint-plugin-import": "^2.8.0",
"eslint-plugin-prettier": "^2.3.0",
"eslint-plugin-react": "^7.3.0",
"eslint-plugin-react": "^7.5.1",
"husky": "^0.14.3",
"intersection-observer": "^0.4.2",
"jest": "^21.0.1",
"intersection-observer": "^0.4.3",
"jest": "^21.2.1",
"lint-staged": "^5.0.0",
"prettier": "^1.6.1",
"react": "^15.4.0",
"react-dom": "^15.4.0",
"react-test-renderer": "^15.6.1",
"prettier": "^1.8.2",
"raf": "^3.4.0",
"react": "^16.1.1",
"react-dom": "^16.1.1",
"react-test-renderer": "^16.1.1",
"rimraf": "^2.6.1",
"standard-version": "^4.2.0",
"style-loader": "^0.19.0",
"validate-commit-msg": "^2.14.0",
"whatwg-fetch": "^2.0.3"
},
"files": [
"lib"
],
"files": ["lib"],
"homepage": "https://github.com/researchgate/react-intersection-list#readme",
"keywords": [
"Intersection",
"Observer",
"react",
"component",
"list",
"infinite",
"scrollable",
"researchgate"
],
"keywords": ["Intersection", "Observer", "react", "component", "list", "infinite", "scrollable", "researchgate"],
"license": "MIT",
"lint-staged": {
"{src,docs/docs}/**/*.js": [
"eslint --fix",
"git add"
]
"{src,docs/docs}/**/*.js": ["eslint --fix", "git add"]
},
"main": "lib/js/index.js",
"module": "lib/es/index.js",
"peerDependencies": {
"react": "^15.4.0",
"react-dom": "^15.4.0"
"react": ">=15",
"react-dom": ">=15"
},
"repository": {
"type": "git",
"url": "https://github.com/researchgate/react-intersection-list"
},
"jest": {
"rootDir": "src",
"testMatch": [
"**/__tests__/**/*.spec.js"
]
"testMatch": ["**/__tests__/**/*.spec.js"],
"setupFiles": ["raf/polyfill"]
},
"scripts": {
"build": "npm run build:js && npm run build:es",
"build:js": "cross-env BABEL_ENV=production BABEL_OUTPUT=cjs babel src --out-dir lib/js --ignore __tests__ --copy-files",
"build:es": "cross-env BABEL_ENV=production BABEL_OUTPUT=esm babel src --out-dir lib/es --ignore __tests__ --copy-files",
"build:js":
"cross-env BABEL_ENV=production BABEL_OUTPUT=cjs babel src --out-dir lib/js --ignore __tests__ --copy-files",
"build:es":
"cross-env BABEL_ENV=production BABEL_OUTPUT=esm babel src --out-dir lib/es --ignore __tests__ --copy-files",
"build:storybook": "build-storybook --output-dir docs",
"create-github-release": "conventional-github-releaser -p angular",
"clear": "rimraf ./lib",
Expand Down
24 changes: 6 additions & 18 deletions src/List.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,13 @@ import Sentinel from './Sentinel';

const AXIS_CSS_MAP = { x: 'overflowX', y: 'overflowY' };

function getLengthProp(props) {
return typeof props.itemsLength !== 'undefined' ? props.itemsLength || 0 : props.currentLength;
}

export default class List extends React.PureComponent {
static propTypes = {
awaitMore: PropTypes.bool,
axis: PropTypes.oneOf(['x', 'y']),
children: PropTypes.func,
initialIndex: PropTypes.number,
currentLength: PropTypes.number,
itemsLength: PropTypes.number,
itemsRenderer: PropTypes.func,
onIntersection: PropTypes.func,
pageSize: PropTypes.number,
Expand All @@ -36,13 +31,8 @@ export default class List extends React.PureComponent {
constructor(props) {
super(props);

warning(
!props.hasOwnProperty('itemsLength'),
'ReactIntersectionList: [deprecation] Use currentLength instead of itemsLength. This prop will be removed in the next major version.',
);

this.state = {
size: this.computeSize(props.pageSize, getLengthProp(props)),
size: this.computeSize(props.pageSize, props.currentLength),
};

this.checkedForIntersection = this.state.size === 0;
Expand All @@ -60,8 +50,7 @@ export default class List extends React.PureComponent {
};

handleUpdate = ({ isIntersecting }) => {
const { pageSize, onIntersection, awaitMore } = this.props;
const currentLength = getLengthProp(this.props);
const { awaitMore, currentLength, onIntersection, pageSize } = this.props;
const { size } = this.state;

if (!this.checkedForIntersection) {
Expand Down Expand Up @@ -92,8 +81,7 @@ export default class List extends React.PureComponent {
}

renderItems() {
const { children, itemsRenderer, initialIndex, threshold, axis, awaitMore } = this.props;
const currentLength = getLengthProp(this.props);
const { awaitMore, axis, children, currentLength, initialIndex, itemsRenderer, threshold } = this.props;
const { size } = this.state;
const items = [];

Expand Down Expand Up @@ -126,9 +114,9 @@ export default class List extends React.PureComponent {
});
}

componentWillReceiveProps({ pageSize, ...nextProps }) {
const currentLength = getLengthProp(this.props);
const nextCurrentLength = getLengthProp(nextProps);
componentWillReceiveProps({ pageSize, ...rest }) {
const { currentLength } = this.props;
const nextCurrentLength = rest.currentLength;

if (this.props.pageSize !== pageSize || currentLength !== nextCurrentLength) {
const nextSize = this.computeSize(this.state.size + pageSize, nextCurrentLength);
Expand Down
2 changes: 1 addition & 1 deletion src/Sentinel.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export default class Sentinel extends React.PureComponent {
rootMargin={rootMargin}
onChange={onChange}
>
<sentinel style={{ height: 1, display: 'block' }} />
<span style={{ height: 1, display: 'block' }} />
</Observer>
);
}
Expand Down
2 changes: 2 additions & 0 deletions src/__mocks__/Sentinel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/* eslint-env jest */
export default jest.genMockFromModule('@researchgate/react-intersection-observer').default;
Loading

0 comments on commit 12ba423

Please sign in to comment.