File tree Expand file tree Collapse file tree 2 files changed +94
-0
lines changed Expand file tree Collapse file tree 2 files changed +94
-0
lines changed Original file line number Diff line number Diff line change
1
+ 'use strict'
2
+ let { useState, useEffect } = require ( 'react' )
3
+ let _throttle = require ( 'lodash.throttle' )
4
+
5
+ let supportsPassive = false
6
+ try {
7
+ var opts = Object . defineProperty ( { } , 'passive' , {
8
+ get : function ( ) {
9
+ supportsPassive = true
10
+ } ,
11
+ } )
12
+ window . addEventListener ( 'testPassive' , null , opts )
13
+ window . removeEventListener ( 'testPassive' , null , opts )
14
+ } catch ( e ) { }
15
+
16
+ let getPosition = ( ) => ( {
17
+ x : window . pageXOffset ,
18
+ y : window . pageYOffset ,
19
+ } )
20
+
21
+ let defaultOptions = {
22
+ throttle : 100 ,
23
+ passive : true ,
24
+ }
25
+
26
+ function useWindowScrollPosition ( options ) {
27
+ let opts = Object . assign ( defaultOptions , options )
28
+
29
+ let [ position , setPosition ] = useState ( getPosition ( ) )
30
+
31
+ useEffect ( ( ) => {
32
+ let handleScroll = _throttle ( ( ) => {
33
+ setPosition ( getPosition ( ) )
34
+ } , opts . throttle )
35
+
36
+ window . addEventListener (
37
+ 'scroll' ,
38
+ handleScroll ,
39
+ supportsPassive && opts . passive ? { passive : true } : false
40
+ )
41
+
42
+ return ( ) => {
43
+ window . removeEventListener ( 'scroll' , handleScroll )
44
+ }
45
+ } )
46
+
47
+ return position
48
+ }
49
+
50
+ module . exports = useWindowScrollPosition
Original file line number Diff line number Diff line change
1
+ {
2
+ "name" : " @rehooks/window-scroll-position" ,
3
+ "version" : " 1.0.0" ,
4
+ "description" : " React hook for Window scroll position" ,
5
+ "main" : " index.js" ,
6
+ "repository" : " https://github.com/rehooks/window-scroll-position" ,
7
+ "author" : " Pave Prichodko" ,
8
+ "license" : " MIT" ,
9
+ "publishConfig" : {
10
+ "access" : " public"
11
+ },
12
+ "keywords" : [
13
+ " react" ,
14
+ " hooks" ,
15
+ " scroll"
16
+ ],
17
+ "files" : [
18
+ " index.*"
19
+ ],
20
+ "scripts" : {
21
+ "test" : " ava test.js" ,
22
+ "example" : " parcel example.html"
23
+ },
24
+ "peerDependencies" : {
25
+ "react" : " ^16.7.0-alpha.0"
26
+ },
27
+ "devDependencies" : {
28
+ "ava" : " ^0.25.0" ,
29
+ "browser-env" : " ^3.2.5" ,
30
+ "parcel" : " ^1.10.3" ,
31
+ "raf" : " ^3.4.0" ,
32
+ "react" : " ^16.7.0-alpha.0" ,
33
+ "react-dom" : " ^16.7.0-alpha.0" ,
34
+ "react-test-renderer" : " ^16.7.0-alpha.0"
35
+ },
36
+ "ava" : {
37
+ "require" : [
38
+ " ./test-setup.js"
39
+ ]
40
+ },
41
+ "dependencies" : {
42
+ "lodash.throttle" : " ^4.1.1"
43
+ }
44
+ }
You can’t perform that action at this time.
0 commit comments