Installations
npm install @healthadvisor/react-in-viewport
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
14.19.1
NPM Version
8.12.1
Score
62.6
Supply Chain
93.1
Quality
78.8
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 (60.06%)
CSS (19.77%)
JavaScript (13.05%)
Shell (6.61%)
HTML (0.51%)
Developer
Download Statistics
Total Downloads
2,520
Last Day
1
Last Week
2
Last Month
3
Last Year
94
GitHub Statistics
349 Stars
204 Commits
30 Forks
3 Watching
4 Branches
13 Contributors
Bundle Size
6.58 kB
Minified
2.22 kB
Minified + Gzipped
Package Meta Information
Latest Version
1.0.0
Package Id
@healthadvisor/react-in-viewport@1.0.0
Unpacked Size
47.01 kB
Size
8.43 kB
File Count
23
NPM Version
8.12.1
Node Version
14.19.1
Total Downloads
Cumulative downloads
Total Downloads
2,520
Last day
0%
1
Compared to previous day
Last week
100%
2
Compared to previous week
Last month
0%
3
Compared to previous month
Last year
-94.2%
94
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Dev Dependencies
39
React In Viewport
Library to detect whether or not a component is in the viewport, using the Intersection Observer API
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');
Difference with original react-in-viewport lib
This fork adds possibility to define IntersectionObserver
's options' root
prop to be a function, which returns a node shortly before creating
new instance of IntersectionObserver
. The reason behind is that if your root might disappear from DOM for any reason, current solution doesn't
handle that and might happen that the observer doesn't react on changing viewport.
Usage:
1import HandleViewport from 'react-in-viewport'; 2 3... 4 5HandleViewport(MyComponent, { 6 root: () => document.getElementById('my-element'), 7});
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 |
Options.root | Node / Function | It should be a DOM node or a function returning the Node |
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 | If you are using a functional component, 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: Stateless: Need to add ref={this.props.forwardedRef}
to your component
Example of a functional component
1import handleViewport from 'react-in-viewport'; 2 3const Block = (props: { inViewport: boolean }) => { 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 } = this.props; 19 return ( 20 <section> 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};
Note
This library is using ReactDOM.findDOMNode
to access the DOM from a React element. This method is deprecated in StrictMode
. We will update the package and release a major version when React 17 is out.
Who is using this component
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
1 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-8hc4-vh64-cxmj
Reason
SAST tool detected but not run on all commits
Details
- Info: SAST configuration detected: CodeQL
- Warn: 16 commits out of 23 are checked with a SAST tool
Reason
5 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 4
Reason
Found 2/13 approved changesets -- score normalized to 1
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
detected GitHub workflow tokens with excessive permissions
Details
- Info: jobLevel 'actions' permission set to 'read': .github/workflows/codeql-analysis.yml:28
- Info: jobLevel 'contents' permission set to 'read': .github/workflows/codeql-analysis.yml:29
- 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
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
4.3
/10
Last Scanned on 2024-12-23
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 More