Installations
npm install react-in-viewport
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
22.11.0
NPM Version
10.9.0
Score
86
Supply Chain
94.7
Quality
85.4
Maintenance
100
Vulnerability
100
License
Releases
v1.0.0-beta-3
Published on 20 Sept 2024
v1.0.0-beta-1
Published on 29 Apr 2024
v1.0.0-alph1.30
Published on 03 Apr 2023
1.0.0-alpha.28
Published on 19 May 2022
v1.0.0-alpha.27
Published on 02 May 2022
v1.0.0-alpha.26
Published on 30 Mar 2022
Contributors
Languages
TypeScript (59.91%)
CSS (19.85%)
JavaScript (13.1%)
Shell (6.63%)
HTML (0.51%)
Developer
Download Statistics
Total Downloads
5,472,861
Last Day
2,735
Last Week
27,806
Last Month
135,191
Last Year
1,648,554
GitHub Statistics
349 Stars
202 Commits
30 Forks
3 Watching
4 Branches
13 Contributors
Package Meta Information
Latest Version
1.0.0-beta.7
Package Id
react-in-viewport@1.0.0-beta.7
Unpacked Size
107.50 kB
Size
18.95 kB
File Count
50
NPM Version
10.9.0
Node Version
22.11.0
Publised On
14 Dec 2024
Total Downloads
Cumulative downloads
Total Downloads
5,472,861
Last day
-61%
2,735
Compared to previous day
Last week
-17.5%
27,806
Compared to previous week
Last month
3.4%
135,191
Compared to previous month
Last year
2.7%
1,648,554
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Dev Dependencies
43
React In Viewport
Library to detect whether or not a component is in the viewport, using the Intersection Observer API.
This library also uses MutationObserver to detect the change of the target element.
npm install --save react-in-viewport
yarn add react-in-viewport
Examples
Why
A common use case is to load an image when a component is in the viewport (lazy load).
We have traditionally needed to monitor scroll position and calculate the viewport size, which can be a scroll performance bottleneck.
Modern browsers now provide a new API--Intersection Observer API--which can make implementating this effort much easier and performant.
Polyfill
For browsers not supporting the API, you will need to load a polyfill. Browser support table
1require('intersection-observer');
Design
The core logic is written using React Hooks. We provide two interfaces: you can use handleViewport
, a higher order component (HOC) for class based components, or use hooks directly, for functional components.
The HOC acts as a wrapper and attaches the intersection observer to your target component. The HOC will then pass down extra props, indicating viewport information and executing a callback function when the component enters and leaves the viewport.
Usages
Using Higher Order Component
When wrapping your component with handleViewport
HOC, you will receive inViewport
props indicating whether the component is in the viewport or not.
handleViewport
HOC accepts three params: handleViewport(Component, Options, Config)
Params | Type | Description |
---|---|---|
Component | React Element | Callback function for when the component enters the viewport |
Options | Object | Options you want to pass to Intersection Observer API |
Config | Object | Configs for HOC (see below) |
Supported config
Params | Type | Default | Description |
---|---|---|---|
disconnectOnLeave | boolean | false | Disconnect intersection observer after leave |
HOC Component Props
Props | Type | Default | Description |
---|---|---|---|
onEnterViewport | function | Callback function for when the component enters the viewport | |
onLeaveViewport | function | Callback function for when the component leaves the viewport |
The HOC preserves onEnterViewport
and onLeaveViewport
props as a callback
Props passed down by HOC to your component
Props | Type | Default | Description |
---|---|---|---|
inViewport | boolean | false | Whether your component is in the viewport |
forwardedRef | React ref | Assign this prop as a ref on your component | |
enterCount | number | Numbers of times your component has entered the viewport | |
leaveCount | number | Number of times your component has left the viewport |
NOTE: Need to add ref={this.props.forwardedRef}
to your component
Example of a functional component
1import handleViewport, { type InjectedViewportProps } from 'react-in-viewport'; 2 3const Block = (props: InjectedViewportProps<HTMLDivElement>) => { 4 const { inViewport, forwardedRef } = props; 5 const color = inViewport ? '#217ac0' : '#ff9800'; 6 const text = inViewport ? 'In viewport' : 'Not in viewport'; 7 return ( 8 <div className="viewport-block" ref={forwardedRef}> 9 <h3>{ text }</h3> 10 <div style={{ width: '400px', height: '300px', background: color }} /> 11 </div> 12 ); 13}; 14 15const ViewportBlock = handleViewport(Block, /** options: {}, config: {} **/); 16 17const Component = (props) => ( 18 <div> 19 <div style={{ height: '100vh' }}> 20 <h2>Scroll down to make component in viewport</h2> 21 </div> 22 <ViewportBlock onEnterViewport={() => console.log('enter')} onLeaveViewport={() => console.log('leave')} /> 23 </div> 24))
Example for enter/leave counts
- If you need to know how many times the component has entered the viewport, use the prop
enterCount
. - If you need to know how many times the component has left the viewport, use the prop
leaveCount
.
1import React, { Component } from 'react'; 2import handleViewport from 'react-in-viewport'; 3 4class MySectionBlock extends Component { 5 getStyle() { 6 const { inViewport, enterCount } = this.props; 7 //Fade in only the first time we enter the viewport 8 if (inViewport && enterCount === 1) { 9 return { WebkitTransition: 'opacity 0.75s ease-in-out' }; 10 } else if (!inViewport && enterCount < 1) { 11 return { WebkitTransition: 'none', opacity: '0' }; 12 } else { 13 return {}; 14 } 15 } 16 17 render() { 18 const { enterCount, leaveCount, forwardedRef } = this.props; 19 return ( 20 <section ref={forwardedRef}> 21 <div className="content" style={this.getStyle()}> 22 <h1>Hello</h1> 23 <p>{`Enter viewport: ${enterCount} times`}</p> 24 <p>{`Leave viewport: ${leaveCount} times`}</p> 25 </div> 26 </section> 27 ); 28 } 29} 30const MySection = handleViewport(MySectionBlock, { rootMargin: '-1.0px' }); 31 32export default MySection;
Using Hooks
Alternatively, you can also directly using useInViewport
hook which takes similar configuration as HOC.
1import React, { useRef } from 'react'; 2import { useInViewport } from 'react-in-viewport'; 3 4const MySectionBlock = () => { 5 const myRef = useRef(); 6 const { 7 inViewport, 8 enterCount, 9 leaveCount, 10 } = useInViewport( 11 myRef, 12 options, 13 config = { disconnectOnLeave: false }, 14 props 15 ); 16 17 return ( 18 <section ref={myRef}> 19 <div className="content" style={this.getStyle()}> 20 <h1>Hello</h1> 21 <p>{`Enter viewport: ${enterCount} times`}</p> 22 <p>{`Leave viewport: ${leaveCount} times`}</p> 23 </div> 24 </section> 25 ); 26};
Who is using this component
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
SAST tool detected but not run on all commits
Details
- Info: SAST configuration detected: CodeQL
- Warn: 15 commits out of 24 are checked with a SAST tool
Reason
3 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-8hc4-vh64-cxmj
- Warn: Project is vulnerable to: GHSA-pxg6-pf52-xh8x
- Warn: Project is vulnerable to: GHSA-rhx6-c78j-4q9w
Reason
3 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 2
Reason
Found 2/11 approved changesets -- score normalized to 1
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Info: jobLevel 'contents' permission set to 'read': .github/workflows/codeql-analysis.yml:29
- Info: jobLevel 'actions' permission set to 'read': .github/workflows/codeql-analysis.yml:28
- Warn: no topLevel permission defined: .github/workflows/build.yml:1
- Warn: no topLevel permission defined: .github/workflows/codeql-analysis.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/build.yml:24: update your workflow using https://app.stepsecurity.io/secureworkflow/roderickhsiao/react-in-viewport/build.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/build.yml:26: update your workflow using https://app.stepsecurity.io/secureworkflow/roderickhsiao/react-in-viewport/build.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:41: update your workflow using https://app.stepsecurity.io/secureworkflow/roderickhsiao/react-in-viewport/codeql-analysis.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:45: update your workflow using https://app.stepsecurity.io/secureworkflow/roderickhsiao/react-in-viewport/codeql-analysis.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:56: update your workflow using https://app.stepsecurity.io/secureworkflow/roderickhsiao/react-in-viewport/codeql-analysis.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:70: update your workflow using https://app.stepsecurity.io/secureworkflow/roderickhsiao/react-in-viewport/codeql-analysis.yml/main?enable=pin
- Info: 0 out of 6 GitHub-owned GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'main'
- Warn: branch protection not enabled for branch '0.x'
Score
3.9
/10
Last Scanned on 2024-12-16
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to react-in-viewport
react-responsive
Media queries in react for responsive design
react-visibility-sensor
Sensor component for React that notifies you when it goes in or out of the window viewport.
react-viewport-utils
Utility components for working with the viewport in react
react-hook-inview
React Hook for detecting when an element is in the viewport