A wrapper component to track if your react component is visible on screen
npm install react-on-screenš Check if your react component are visible on the screen without pain and with performance in mind š!
- [React on screen ![npm]() ![npm]() ![license]() !Coverage Status](#react-on-screen-npm-npm-license-coverage-statushttpscoverallsiogithubfkhadrareact-on-screenbranchmaster)
- Demo
- Installation
- Usage
- Simple
- Using a render props
- Track the visibility only once
- Defining offset
- Partial visibility
- Use the html tag of your choice
- Api
- Contributions
- License
View the demo.
```
$ npm install --save react-on-screen
$ yarn add react-on-screen
A UMD build is also available :
`html`
`javascript
import React from 'react';
import TrackVisibility from 'react-on-screen';
const ComponentToTrack = ({ isVisible }) => {
const style = {
background: isVisible ? 'red' : 'blue'
};
return
const YourApp = () => {
return (
{/ Some Stuff /}
{/ Some Stuff /}
);
}
`
You can use a render props is you want to !
`js`
const YourApp = () => {
return (
{({ isVisible }) => isVisible &&
);
}
For many cases you may want to track the visibility only once. This can be done simply as follow :
`js`
const YourApp = () => {
return (
);
}
Using offset props can be usefull if you want to lazy load an image for instance.
`js`
const YourApp = () => {
return (
{({ isVisible }) => isVisible ?
);
}
You may want to consider that a component is visible as soon as a part of the component is visible on screen. You can use the partialVisibility props for that.
`js`
const YourApp = () => {
return (
{({ isVisible }) =>
);
}
`js`
const YourApp = () => {
return (
{({ isVisible }) =>
);
}
|props |type |default|description|
|----------------|----------------|-------|-----------|
|once |bool |false|If set to true track the visibility only once and remove the event listeners|
|throttleInterval|int |150|Tweak the event listeners. See David Corbacho's article|
|children |React Components| - |Can be one or many react components|
|style |object | - |Style attributes|
|className |string | - |Css classes|
|offset |number | 0 |Allows you to specify how far left or above of the viewport you want to set isVisible to true|
|partialVisibility|bool |false|Set isVisible to true on element as soon as any part is in the viewport|
|tag |string|div |Allows specifying html tag of your choice|
Any contributions is welcome !
- Develop: ` $ yarn start ``
- Lint : $ yarn lint ``
- Test : $ yarn test ``
- Build : $ yarn build // will lint and run test before ``
Licensed under MIT