A simple library that lets you know whether a Component is visible or not.
npm install react-is-visible

A small library that lets you know whether a component is visible on screen or not.
Uses the IntersectionObserver API.
Storybook: https://lessp.github.io/react-is-visible/
Code Sandbox: https://2c2qy.csb.app/

1. Polyfill
2. Installation
3. Usage
- React Hook
- HOC
- Render Prop
4. License
In order to polyfill, install the polyfill from W3C
$ npm install intersection-observer --save
... and import it before importing 'react-is-visible'
eg.
``jsx
// App.js
import React from 'react'
import ReactDOM from 'react-dom'
import 'intersection-observer'
import { withIsVisible } from 'react-is-visible'
// ...
`
$ npm install react-is-visible --save
or
$ yarn add react-is-visible
#### React Hook
`jsx
import React, { useRef } from 'react'
import { useIsVisible } from 'react-is-visible'
const SomeComponent = () => {
const nodeRef = useRef()
const isVisible = useIsVisible(nodeRef)
/ const isVisible = useIsVisible(nodeRef, { once: true }) /
return
}#### HOC
`jsx
import React from 'react'
import { withIsVisible } from 'react-is-visible'const SomeComponent = ({ isVisible }) =>
{isVisible &&
I'm visible!}export default withIsVisible(SomeComponent)
/ export default withIsVisible(SomeComponent, { once: true }) /
`or as a decorator
`jsx
import React from 'react'
import { withIsVisible } from 'react-is-visible'@withIsVisible
class SomeClass extends React.Component {
render() {
const { isVisible } = this.props
return
{isVisible &&
I'm visible!}
}
}
`#### Render Prop
The
once-prop is optional, but if passed, the isVisible-flag will only trigger once.`jsx
import React from 'react'
import IsVisible from 'react-is-visible'const App = () => (
{(isVisible) => {isVisible ?
I'm visible! : I'm not visible!}}
)
``MIT