https://github.com/olistic/react-use-visibility
React hook for tracking components visibility
https://github.com/olistic/react-use-visibility
hooks react
Last synced: about 1 year ago
JSON representation
React hook for tracking components visibility
- Host: GitHub
- URL: https://github.com/olistic/react-use-visibility
- Owner: olistic
- License: mit
- Created: 2018-10-31T20:28:13.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2023-01-04T02:07:53.000Z (over 3 years ago)
- Last Synced: 2025-04-19T23:33:32.402Z (about 1 year ago)
- Topics: hooks, react
- Language: JavaScript
- Size: 585 KB
- Stars: 26
- Watchers: 2
- Forks: 1
- Open Issues: 12
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# react-use-visibility
React hook for tracking components visibility.
[![Travis][build-badge]][build] [![Codecov][codecov-badge]][codecov]

> _Electrons becoming excited as they enter the screen._
## Installation
```sh
$ npm install --save react-use-visibility
```
Additionally, you'll need to install version `16.7.0-alpha.0` of `react` and
`react-dom` since this package relies on
[React Hooks](https://reactjs.org/hooks):
```sh
$ npm install --save react@16.7.0-alpha.0 react-dom@16.7.0-alpha.0
```
> **DISCLAIMER:** React Hooks are an experimental proposal. The Hooks API, as
> well as this library's, are unstable and subject to change.
## Usage
```js
import React, { useRef } from 'react';
import useVisibility from 'react-use-visibility';
function Electron() {
// Use a ref to attach to the element whose visibility you want to keep track of.
const imgRef = useRef();
// `current` points to the mounted img element.
const isVisible = useVisibility(imgRef.current);
return (
);
}
```
## API Reference
### `useVisibility`
```js
const isVisible = useVisibility(el, options);
```
Accepts a React element as the first argument (`el`) and returns whether it is
on the screen or not.
Optionally, you can pass a second argument to `useVisibility` that is an object
with the following properties:
- `partial` (_boolean_): Whether to consider the element visible when only a
part of it is on the screen. Defaults to `false`.
- `scrollableEl` (_Element_): The parent element triggering the scroll event.
Defaults to `window`.
[build-badge]:
https://img.shields.io/travis/olistic/react-use-visibility/master.svg
[build]: https://travis-ci.org/olistic/react-use-visibility
[codecov-badge]:
https://img.shields.io/codecov/c/github/olistic/react-use-visibility/master.svg
[codecov]: https://codecov.io/gh/olistic/react-use-visibility