Skip to content

Rewrite visibility sensor to hooks #161

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

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open
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
93 changes: 71 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
React Visibility Sensor
====
# React Visibility Sensor

[![Build Status](https://secure.travis-ci.org/joshwnj/react-visibility-sensor.png)](http://travis-ci.org/joshwnj/react-visibility-sensor)

Sensor component for React that notifies you when it goes in or out of the window viewport.

Sponsored by [X-Team](https://x-team.com)

Install
----
## Install

`npm install react-visibility-sensor`

Expand All @@ -23,8 +21,7 @@ In this case, make sure that `React` and `ReactDOM` are already loaded and globa

Take a look at the [umd example](./example-umd/) to see this in action

Example
----
## Example

[View an example on codesandbox](https://codesandbox.io/s/p73kyx9zpm)

Expand All @@ -40,13 +37,13 @@ To run the example locally:
General usage goes something like:

```js
const VisibilitySensor = require('react-visibility-sensor');
import VisibilitySensor from "react-visibility-sensor";

function onChange (isVisible) {
console.log('Element is now %s', isVisible ? 'visible' : 'hidden');
function onChange(isVisible) {
console.log("Element is now %s", isVisible ? "visible" : "hidden");
}

function MyComponent (props) {
function MyComponent(props) {
return (
<VisibilitySensor onChange={onChange}>
<div>...content goes here...</div>
Expand All @@ -55,25 +52,79 @@ function MyComponent (props) {
}
```

### Child Function syntax

You can also pass a child function, which can be convenient if you don't need to store the visibility anywhere:

```js
function MyComponent (props) {
import VisibilitySensor from "react-visibility-sensor";

function MyComponent(props) {
return (
<VisibilitySensor>
{({isVisible}) =>
<div>I am {isVisible ? 'visible' : 'invisible'}</div>
}
{({ isVisible, visibilityRect }) => (
<div>I am {isVisible ? "visible" : "invisible"}</div>
)}
</VisibilitySensor>
);
}
```

Props
----
The child function must return an element. The 3 arguments that you can access from the child function are:

- `isVisible`: Boolean
- `visibilityRect`: an Object indicating which sides of the element are visible, in the shape of:

```
{
top: Boolean,
bottom: Boolean,
left: Boolean,
right: Boolean
}
```

---

### React hook syntax

For more control on the nodeRef, you can use the React hook directly and attach it to the element:

```js
import { useVisibilitySensor } from "react-visibility-sensor";

function MyComponent(props) {
const onChange = useCallback(isVisible => {
console.log(`Visibility changed! ${isVisible ? "visible" : "invisible"}`);
}, []);
const { nodeRef, isVisible } = useVisibilitySensor({ onChange });
return <div ref={nodeRef}>I am {isVisible ? "visible" : "invisible"}</div>;
}
```

The useVisibilitySensor hook returns an object containing:

- `nodeRef`: Object, React ref instance to be attached to the element.
- `isVisible`: Boolean
- `visibilityRect`: Object, indicating which sides of the element are visible, in the shape of:

```
{
top: Boolean,
bottom: Boolean,
left: Boolean,
right: Boolean
}
```

---

## Props

Most of the properties can be used for both `VisibilitySensor` Component and `useVisibilitySensor` hook.

- `onChange`: callback for whenever the element changes from being within the window viewport or not. Function is called with 1 argument `(isVisible: boolean)`
- `active`: (default `true`) boolean flag for enabling / disabling the sensor. When `active !== true` the sensor will not fire the `onChange` callback.
- `active`: (default `true`) boolean flag for enabling / disabling the sensor. When `active !== true` the sensor will not fire the `onChange` callback. **When using hooks create the onChange function using useCallback to avoid performance issues.**
- `partialVisibility`: (default `false`) consider element visible if only part of it is visible. Also possible values are - 'top', 'right', 'bottom', 'left' - in case it's needed to detect when one of these become visible explicitly.
- `offset`: (default `{}`) with offset you can define amount of px from one side when the visibility should already change. So in example setting `offset={{top:10}}` means that the visibility changes hidden when there is less than 10px to top of the viewport. Offset works along with `partialVisibility`
- `minTopValue`: (default `0`) consider element visible if only part of it is visible and a minimum amount of pixels could be set, so if at least 100px are in viewport, we mark element as visible.
Expand All @@ -87,16 +138,14 @@ Props
- `resizeThrottle`: (default: `-1`) by specifying a value > -1, you are enabling throttle instead of the delay to trigger checks on resize event. Throttle supercedes delay.
- `containment`: (optional) element to use as a viewport when checking visibility. Default behaviour is to use the browser window as viewport.
- `delayedCall`: (default `false`) if is set to true, wont execute on page load ( prevents react apps triggering elements as visible before styles are loaded )
- `children`: can be a React element or a function. If you provide a function, it will be called with 1 argument `{isVisible: ?boolean, visibilityRect: Object}`
- `children`: **Only for `VisibilitySensor` Component** can be a React element or a function. If you provide a function, it will be called with 1 argument `{isVisible: ?boolean, visibilityRect: Object}`

It's possible to use both `intervalCheck` and `scrollCheck` together. This means you can detect most visibility changes quickly with `scrollCheck`, and an `intervalCheck` with a higher `intervalDelay` will act as a fallback for other visibility events, such as resize of a container.

Thanks
----
## Thanks

Special thanks to [contributors](https://github.com/joshwnj/react-visibility-sensor/graphs/contributors)

License
----
## License

MIT
4 changes: 2 additions & 2 deletions example-umd/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@
<div class="inner"></div>
</div>
</div>
<script src="https://unpkg.com/react@0.14.8/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom@0.14.8/dist/react-dom.min.js"></script>
<script src="https://unpkg.com/react@16.8.6/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.8.6/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/visibility-sensor.min.js"></script>
<script src="./main.js"></script>
</body>
Expand Down
97 changes: 53 additions & 44 deletions example/main.js
Original file line number Diff line number Diff line change
@@ -1,49 +1,60 @@
"use strict";

import React from "react";
import React, { useState, useCallback } from "react";
import ReactDOM from "react-dom";
import VisibilitySensor from "../visibility-sensor";

class Example extends React.Component {
constructor(props) {
super(props);

this.state = {
msg: ""
};
}

onChange = isVisible => {
this.setState({
msg: "Element is now " + (isVisible ? "visible" : "hidden")
});
};

render() {
return (
<div>
<p className="msg">{this.state.msg}</p>
<div className="before" />
<VisibilitySensor
scrollCheck
scrollThrottle={100}
intervalDelay={8000}
containment={this.props.containment}
onChange={this.onChange}
minTopValue={this.props.minTopValue}
partialVisibility={this.props.partialVisibility}
offset={this.props.offset}
>
<div className="sensor" />
</VisibilitySensor>
<div className="after" />
</div>
);
}
import VisibilitySensor, { useVisibilitySensor } from "../visibility-sensor";

function RegularExample({ containment, minTopValue, partialVisibility }) {
const [msg, setMsg] = useState("");
const onChange = useCallback(isVisible => {
setMsg("Element is now " + (isVisible ? "visible" : "hidden"));
}, []);

return (
<div>
<p className="msg">{msg}</p>
<div className="before" />
<VisibilitySensor
scrollCheck={true}
scrollThrottle={100}
intervalDelay={8000}
onChange={onChange}
>
{() => <div className="sensor" />}
</VisibilitySensor>
<div className="after" />
</div>
);
}

function HookExample({ containment, minTopValue, partialVisibility }) {
const [msg, setMsg] = useState("");
const onChange = useCallback(isVisible => {
setMsg("Element is now " + (isVisible ? "visible" : "hidden"));
}, []);

const { nodeRef } = useVisibilitySensor({
scrollCheck: true,
scrollThrottle: 100,
intervalDelay: 8000,
containment,
minTopValue: 10,
partialVisibility: true,
onChange
});

return (
<div>
<p className="msg">{msg}</p>
<div className="before" />
<div ref={nodeRef} className="sensor" />
<div className="after" />
</div>
);
}

ReactDOM.render(
React.createElement(Example),
React.createElement(RegularExample),
document.getElementById("example")
);

Expand All @@ -54,10 +65,8 @@ container.scrollTop = 320;
container.scrollLeft = 320;

ReactDOM.render(
React.createElement(Example, {
containment: container,
minTopValue: 10,
partialVisibility: true
React.createElement(HookExample, {
containment: container
}),
elem
);
35 changes: 0 additions & 35 deletions lib/is-visible-with-offset.js

This file was deleted.

Loading