├── .editorconfig
├── .gitignore
├── .npmignore
├── .prettierignore
├── .prettierrc
├── LICENSE
├── README.md
├── index.ts
├── package-lock.json
├── package.json
└── tsconfig.json
/.editorconfig:
--------------------------------------------------------------------------------
1 | # http://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | end_of_line = lf
7 | indent_size = 2
8 | indent_style = space
9 | insert_final_newline = true
10 | trim_trailing_whitespace = true
11 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | *.js
3 | *.d.ts
4 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | .*
2 |
--------------------------------------------------------------------------------
/.prettierignore:
--------------------------------------------------------------------------------
1 | tsconfig.json
2 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "singleQuote": true,
3 | "printWidth": 120
4 | }
5 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Wenchen Li
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-use-scroll-position
2 |
3 | [](https://www.npmjs.com/package/react-use-scroll-position) 
4 |
5 | A [react hook](https://reactjs.org/docs/hooks-intro.html) to use scroll position.
6 |
7 | ## Usage
8 |
9 | ### In a React functional component:
10 |
11 | ```tsx
12 | import React from 'react';
13 | // Usually you would just need to import one of the following
14 | import { useScrollPosition, useScrollXPosition, useScrollYPosition } from 'react-use-scroll-position';
15 |
16 | function Example() {
17 | const { x, y } = useScrollPosition();
18 | const scrollX = useScrollXPosition();
19 | const scrollY = useScrollYPosition();
20 | return (
21 | <>
22 |
23 | {x} should equal to {scrollX}.
24 |
25 |
26 | {y} should equal to {scrollY}.
27 |
28 | >
29 | );
30 | }
31 | ```
32 |
33 | ### In a custom React hook
34 |
35 | ```tsx
36 | import { useScrollPosition } from 'react-use-scroll-position';
37 |
38 | function useYourImagination() {
39 | const { x, y } = useScrollPosition();
40 | return getSomethingAwesomeWith(x, y);
41 | }
42 | ```
43 |
44 | # Implementation details
45 |
46 | The scroll event handler is throttled by `requestAnimationFrame`.
47 |
--------------------------------------------------------------------------------
/index.ts:
--------------------------------------------------------------------------------
1 | import { useState, useEffect } from 'react';
2 |
3 | interface ScrollPosition {
4 | x: number;
5 | y: number;
6 | }
7 |
8 | const isBrowser = typeof window !== `undefined`;
9 |
10 | function getScrollPosition(): ScrollPosition {
11 | return isBrowser ? { x: window.pageXOffset, y: window.pageYOffset } : { x: 0, y: 0 };
12 | }
13 |
14 | export function useScrollPosition(): ScrollPosition {
15 | const [position, setScrollPosition] = useState(getScrollPosition());
16 |
17 | useEffect(() => {
18 | let requestRunning: number | null = null;
19 | function handleScroll() {
20 | if (isBrowser && requestRunning === null) {
21 | requestRunning = window.requestAnimationFrame(() => {
22 | setScrollPosition(getScrollPosition());
23 | requestRunning = null;
24 | });
25 | }
26 | }
27 |
28 | if (isBrowser) {
29 | window.addEventListener('scroll', handleScroll);
30 | return () => window.removeEventListener('scroll', handleScroll);
31 | }
32 | }, []);
33 |
34 | return position;
35 | }
36 |
37 | export function useScrollXPosition(): number {
38 | const { x } = useScrollPosition();
39 | return x;
40 | }
41 |
42 | export function useScrollYPosition(): number {
43 | const { y } = useScrollPosition();
44 | return y;
45 | }
46 |
--------------------------------------------------------------------------------
/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-use-scroll-position",
3 | "version": "2.0.0",
4 | "lockfileVersion": 1,
5 | "requires": true,
6 | "dependencies": {
7 | "@types/prop-types": {
8 | "version": "15.7.1",
9 | "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.1.tgz",
10 | "integrity": "sha512-CFzn9idOEpHrgdw8JsoTkaDDyRWk1jrzIV8djzcgpq0y9tG4B4lFT+Nxh52DVpDXV+n4+NPNv7M1Dj5uMp6XFg==",
11 | "dev": true
12 | },
13 | "@types/react": {
14 | "version": "16.8.19",
15 | "resolved": "https://registry.npmjs.org/@types/react/-/react-16.8.19.tgz",
16 | "integrity": "sha512-QzEzjrd1zFzY9cDlbIiFvdr+YUmefuuRYrPxmkwG0UQv5XF35gFIi7a95m1bNVcFU0VimxSZ5QVGSiBmlggQXQ==",
17 | "dev": true,
18 | "requires": {
19 | "@types/prop-types": "*",
20 | "csstype": "^2.2.0"
21 | }
22 | },
23 | "csstype": {
24 | "version": "2.6.5",
25 | "resolved": "https://registry.npmjs.org/csstype/-/csstype-2.6.5.tgz",
26 | "integrity": "sha512-JsTaiksRsel5n7XwqPAfB0l3TFKdpjW/kgAELf9vrb5adGA7UCPLajKK5s3nFrcFm3Rkyp/Qkgl73ENc1UY3cA==",
27 | "dev": true
28 | },
29 | "js-tokens": {
30 | "version": "4.0.0",
31 | "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
32 | "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
33 | "dev": true
34 | },
35 | "loose-envify": {
36 | "version": "1.4.0",
37 | "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
38 | "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
39 | "dev": true,
40 | "requires": {
41 | "js-tokens": "^3.0.0 || ^4.0.0"
42 | }
43 | },
44 | "object-assign": {
45 | "version": "4.1.1",
46 | "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
47 | "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=",
48 | "dev": true
49 | },
50 | "prop-types": {
51 | "version": "15.7.2",
52 | "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.7.2.tgz",
53 | "integrity": "sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==",
54 | "dev": true,
55 | "requires": {
56 | "loose-envify": "^1.4.0",
57 | "object-assign": "^4.1.1",
58 | "react-is": "^16.8.1"
59 | }
60 | },
61 | "react": {
62 | "version": "16.8.6",
63 | "resolved": "https://registry.npmjs.org/react/-/react-16.8.6.tgz",
64 | "integrity": "sha512-pC0uMkhLaHm11ZSJULfOBqV4tIZkx87ZLvbbQYunNixAAvjnC+snJCg0XQXn9VIsttVsbZP/H/ewzgsd5fxKXw==",
65 | "dev": true,
66 | "requires": {
67 | "loose-envify": "^1.1.0",
68 | "object-assign": "^4.1.1",
69 | "prop-types": "^15.6.2",
70 | "scheduler": "^0.13.6"
71 | }
72 | },
73 | "react-is": {
74 | "version": "16.8.6",
75 | "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.8.6.tgz",
76 | "integrity": "sha512-aUk3bHfZ2bRSVFFbbeVS4i+lNPZr3/WM5jT2J5omUVV1zzcs1nAaf3l51ctA5FFvCRbhrH0bdAsRRQddFJZPtA==",
77 | "dev": true
78 | },
79 | "scheduler": {
80 | "version": "0.13.6",
81 | "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.13.6.tgz",
82 | "integrity": "sha512-IWnObHt413ucAYKsD9J1QShUKkbKLQQHdxRyw73sw4FN26iWr3DY/H34xGPe4nmL1DwXyWmSWmMrA9TfQbE/XQ==",
83 | "dev": true,
84 | "requires": {
85 | "loose-envify": "^1.1.0",
86 | "object-assign": "^4.1.1"
87 | }
88 | },
89 | "typescript": {
90 | "version": "3.5.1",
91 | "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.5.1.tgz",
92 | "integrity": "sha512-64HkdiRv1yYZsSe4xC1WVgamNigVYjlssIoaH2HcZF0+ijsk5YK2g0G34w9wJkze8+5ow4STd22AynfO6ZYYLw==",
93 | "dev": true
94 | }
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-use-scroll-position",
3 | "version": "2.0.0",
4 | "description": "A react hook to use scroll position",
5 | "main": "index.js",
6 | "types": "index.d.ts",
7 | "scripts": {
8 | "build": "tsc",
9 | "prepare": "npm run build",
10 | "test": "echo \"Error: no test specified\" && exit 1"
11 | },
12 | "repository": {
13 | "type": "git",
14 | "url": "git+https://github.com/neo/react-use-scroll-position.git"
15 | },
16 | "keywords": [
17 | "scroll",
18 | "position",
19 | "react",
20 | "hook",
21 | "scroll position",
22 | "react hook"
23 | ],
24 | "author": "Wenchen Li (https://wenchen.li/)",
25 | "license": "MIT",
26 | "bugs": {
27 | "url": "https://github.com/neo/react-use-scroll-position/issues"
28 | },
29 | "homepage": "https://github.com/neo/react-use-scroll-position#readme",
30 | "peerDependencies": {
31 | "react": ">=16.8.0"
32 | },
33 | "devDependencies": {
34 | "@types/react": "^16.8.19",
35 | "react": "^16.8.6",
36 | "typescript": "^3.5.1"
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Basic Options */
4 | "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
5 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
6 | "lib": ["dom", "es2015"], /* Specify library files to be included in the compilation. */
7 | // "allowJs": true, /* Allow javascript files to be compiled. */
8 | // "checkJs": true, /* Report errors in .js files. */
9 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
10 | "declaration": true, /* Generates corresponding '.d.ts' file. */
11 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
12 | // "sourceMap": true, /* Generates corresponding '.map' file. */
13 | // "outFile": "./", /* Concatenate and emit output to single file. */
14 | // "outDir": "./", /* Redirect output structure to the directory. */
15 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
16 | // "composite": true, /* Enable project compilation */
17 | // "removeComments": true, /* Do not emit comments to output. */
18 | // "noEmit": true, /* Do not emit outputs. */
19 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */
20 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
21 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
22 |
23 | /* Strict Type-Checking Options */
24 | "strict": true, /* Enable all strict type-checking options. */
25 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
26 | // "strictNullChecks": true, /* Enable strict null checks. */
27 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */
28 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
29 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
30 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
31 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
32 |
33 | /* Additional Checks */
34 | "noUnusedLocals": true, /* Report errors on unused locals. */
35 | "noUnusedParameters": true, /* Report errors on unused parameters. */
36 | "noImplicitReturns": false, /* Report error when not all code paths in function return a value. */
37 | "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
38 |
39 | /* Module Resolution Options */
40 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
41 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
42 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
43 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
44 | // "typeRoots": [], /* List of folders to include type definitions from. */
45 | // "types": [], /* Type declaration files to be included in compilation. */
46 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
47 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
48 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
49 |
50 | /* Source Map Options */
51 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
52 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
53 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
54 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
55 |
56 | /* Experimental Options */
57 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
58 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
59 | }
60 | }
61 |
--------------------------------------------------------------------------------